为什么我会收到错误"Floating point exception"?

Why do I get the error "Floating point exception"?

本文关键字:Floating point exception 错误 为什么      更新时间:2023-10-16

我试图写一个代码,找到完美的数字低于用户的输入。正确输出示例:

输入正整数:100
6是一个完全数
28是一个完全数
再没有小于等于100的完全数

但是当我运行我的代码时,我得到错误Floating point exception

,不知道为什么。我做错了什么?

下面是我的代码:
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main(){
    int x, y;
    int countOut, countIn;
    int userIn;
    int perfect = 0;
    cout << "Enter a positive integer: ";
    cin >> userIn;
    for(countOut = 0; countOut < userIn; countOut++){
        for(countIn = 1; countIn <= countOut; countIn++){
            if(isAFactor(countOut, countIn) == true){
                countOut = countOut + perfect;
            }
        }
        if(perfect == countOut){
            cout << perfect << " is a perfect number" << endl;
        }
        perfect++;
    }
    cout << "There are no more perfect numbers less than or equal to " << userIn << endl;
    return 0;
}

bool isAFactor(int inner, int outer){
    if(outer % inner == 0){
        return true;
    }
    else{
        return false;
    }
}

只是交换了参数。当您应该调用isAFactor(countIn, countOut)时,您正在调用isAFactor(countOut, countIn)函数

澄清@Aki Suihkonen的评论,在表演时:outer % inner如果inner为零,您将得到一个除以零错误。

这可以通过调用isAFactor(0, 1)来反向跟踪。它在mainfor循环中。

isAFactor(countOut, countIn)的第一个形参在最外层的for循环中赋值:for (countOut = 0; ...

注意您初始化countOut时使用的值。

编辑1:

Change your `isAFactor` function to:  
    if (inner == 0)
    {
       cerr << "Divide by zero.n";
       cerr.flush();
       return 0;
    }
    if (outer % inner ...

cerr以上任意一行设置一个断点。
当执行停止时,查看堆栈跟踪。一个好的调试器还允许您在跟踪的每个点检查参数/值。