0

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

输入一个正整数: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;
    }
}
4

2 回答 2

1

只是交换了论点。您正在调用该函数,因为isAFactor(countOut, countIn)您应该调用isAFactor(countIn, countOut)

于 2013-04-21T18:14:47.840 回答
0

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

这可以通过调用来追溯isAFactor(0, 1)
它在你的for循环中main

第一个参数 to在最外层循环 isAFactor(countOut, countIn)中赋值:forfor (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在上面的任一行放置一个断点。
当执行在那里停止时,查看Stack Trace。一个好的调试器还允许您检查跟踪中每个点的参数/值。

于 2013-04-21T18:27:02.087 回答