the*_*224 0 c++ math for-loop divide-by-zero dividebyzeroexception
我正在开发一个非常小的程序来查找C++中整数的除数.我的main方法几乎将int转换为var,并使用int作为参数调用factor方法.这是代码:
void factor(int num)
{
for(int x = 0; x < ((num + 2) / 2); x++)
{
if((num % x) == 0)
{
cout << x << " ";
}
}
}
Run Code Online (Sandbox Code Playgroud)
程序总是在factor()内崩溃.如果我使用此代码,它运行正常:
void factor(int num)
{
for(int x = 0; x < ((num + 2) / 2); x++)
{
{
cout << x << " ";
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以问题出在了if((num % x) == 0).当我将该行更改为if((num % 2) == 0)或时if((num % 5) == 0),它会产生正确的结果(我使用32作为测试输入).
几年前我学习了C++并且忘记了大部分内容,在遇到这个问题之后,我逐字逐句地复制了代码中的这个问题(这有效).但是每当我尝试访问循环计数器时程序仍会崩溃.
我在Arch Linux 64位上使用Code :: Blocks 13.12和GCC"4.9.0 20140604(预发布)".
问题是你的第一个片段中有一个除零,这是根据标准(n3337)未定义的行为:
5.6p4乘法运算符[expr.mul]二元
/运算符产生商,二元%运算符将第一个表达式除以第二个表达式的余数生成.如果第二个操作数为/或%为零,则行为未定义.
由于程序无法计算此类表达式的值,因此会崩溃.
if((num % x) == 0) // num % 0 on first iteration, application will crash, or order pizza
{
cout << x << " ";
}
Run Code Online (Sandbox Code Playgroud)