我得到一个除以零错误,但无法弄清楚为什么
I am getting a Divide by zero error but can't figure out why
错误发生在以下行:
return(rand()% sides + 1);
这是我的程序:
// main.cpp
// dcChecker
//
// Created by Max Huber on 2/21/13.
// Copyright (c) 2013 S0URC3 Studioss. All rights reserved.
//
#include <iostream>
#include <ctime>
#include <cstdlib>
int rollDice(int);
int diceCheck(int diceMod, int dci, int roll);
void clearScreen();
void pressEnter();
void dcFunction();
int main()
{
dcFunction();
clearScreen();
main();
}
// Roll a n sided die
int rollDice(int sides)
{
//int gen;
//create time variable
time_t timer;
//set time variable to current time in seconds
time(&timer);
//seed random number generator using current time in seconds
srand(timer);
//generate random number
//gen = (rand()% sides + 1);
return(rand()% sides + 1);
}
// Check if the dice roll + modifier (if any) is greater than the check value
int diceCheck(int diceMod, int dci, int roll)
{
if(roll + diceMod >= dci)
{
return 0;
}
else
return 1;
}
void clearScreen()
{
#ifdef WINDOWS
std::system ( "CLS" );
#else
// Assume POSIX
std::system ( "clear" );
#endif
}
void pressEnter()
{
std::cin.sync();
std::cout << std::endl << "Press ENTER to continue..." << std::endl;
std::cin.get();
}
void dcFunction()
{
//define variables
int neededRoll;
int diceMod;
int sides;
int roll;
//get user inputs
std::cout << "How many sides: ";
std::cin >> sides;
std::cout << "Enter needed roll: ";
std::cin >> neededRoll;
std::cout << "Enter dice modifiers: ";
std::cin >> diceMod;
//store roll in variable so it can be gotten later
roll = rollDice(sides);
//check if your roll was better than the dice check
//success check
if(diceCheck(diceMod, neededRoll, roll) == 0)
{
std::cout << "nSUCCESSnn"
<< "You rolled a " << sides << " sided dien"
<< "You rolled: " << roll << " + " << diceMod << " = " << roll + diceMod << "n"
<< "You needed: " << neededRoll << "n";
}
//otherwise you fail
else
{
std::cout << "nFAILURE!!!nn"
<< "You rolled a " << sides << " sided dien"
<< "You rolled: " << roll << " + " << diceMod << " = " << roll + diceMod << "n"
<< "You needed: " << neededRoll << "n";
}
pressEnter();
}
可能在return(rand()% sides + 1);
模也可以导致被零除,并且它的优先级高于加法。你实际上是在说return (rand() % sides) + 1;
,如果sides
是0
,那么你就会得到异常。
相关文章:
- 我的字符计数代码计算错误.为什么
- C++ 错误 为什么这个矢量不输出?
- 当在函数调用中递增值时,程序正常工作,但是如果我们在单独的行中增加值而不是呼叫函数,则会出现错误.为什么
- 我正在将QPixmap传递给QAbstractButton::setIcon而不是QIcon,但我没有得到错误...为什么?
- 在 ZeroMQ 中绑定订阅者套接字并连接发布者套接字会在代码运行时给出错误.为什么
- 分段错误:为什么这里的数组索引越界了
- Box2D不寻常的错误.为什么 0阻止错误
- c++分段错误:为什么这个程序给出运行时错误(SIGSEGV)
- 链接列表错误 - 为什么头和尾引用指向相同地址
- VC++的一个大错误?为什么初始值设定项列表不对结构进行值初始化
- 分配大量内存会产生错误?为什么
- 得到一个段错误.为什么
- 变量名称与函数名称相同,导致编译器错误.为什么
- 访问在相应类的静态函数中创建的对象的私有成员变量不会导致错误.为什么?
- Qt5:此代码使用msvc2012编译正常,但使用MinGW编译时出现错误..为什么?
- 奇怪的错误-为什么编译器试图调用复制构造函数
- 我在使用 std::map 时收到此错误.为什么
- 我写了这个程序来反转链表中的元素,在编译这个程序后,在reverse()中显示错误.为什么
- Valgrind报告写入错误?为什么?
- 编译器错误 - 为什么我不能在Sublime Text 2中构建C++?