为什么我会收到错误"浮点异常"?

时间:2013-04-21 17:40:02

标签: c++ perfect-numbers

我正在尝试编写一个代码,找到比用户输入更低的完美数字。 正确输出的样本:

  

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

2 个答案:

答案 0 :(得分:1)

参数刚刚被交换。当您应该使用isAFactor(countOut, countIn)

进行呼叫时,您正在将该功能调用为isAFactor(countIn, countOut)

答案 1 :(得分:0)

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

这可以通过调用isAFactor(0, 1)来追溯 它位于for的{​​{1}}循环中。

main的第一个参数在最外面的isAFactor(countOut, countIn)循环中分配: for

注意您使用。{/ p>初始化for (countOut = 0; ...的值

修改1:

countOut

在上方的Change your `isAFactor` function to: if (inner == 0) { cerr << "Divide by zero.\n"; cerr.flush(); return 0; } if (outer % inner ... 行放置一个断点 当执行停止时,请查看堆栈跟踪。一个好的调试器还允许您检查跟踪中每个点的参数/值。

相关问题