小编the*_*224的帖子

在循环内使用计数器时,C++程序崩溃

我正在开发一个非常小的程序来查找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++ math for-loop divide-by-zero dividebyzeroexception

0
推荐指数
1
解决办法
186
查看次数