0

我必须编写一个程序,在用户给定的特定范围内检查“完美数字”。我做了一个用户定义的函数来检查一个特定的数字是否是一个完美的数字。如果是则返回 1,如果不是则返回 0。然后我使用 if 语句在主程序中打印出完美数字。我遇到的问题是浮点异常错误。我不知道现在该怎么办。我会非常感谢一些帮助。:)。

#include <iostream>
using namespace std;

int isPerfect(int n);

int main(){
    int num=0,perfectCheck=0;
    cout<<"Enter a value for N: ";
    cin>>num;
    cout<<"Perect numbers between 1 and "<<num<<" are : "<<endl;
    for(int i;i<=num;i++){
        perfectCheck=isPerfect(i);
        if(perfectCheck==1){
              cout<<i<<endl;
        }   
    }
    return 0;
}

int isPerfect(int n){
    int sum,mod;
    for(int i;i<n;i++){
        mod=n%i;
        if(mod==0){
            sum=sum+i;
        }
    }
    if(sum==n){
         return 1;
    }
    else{
        return 0;
    }
}
4

1 回答 1

1

isPerfect 函数中的 for 循环应该从 1 开始,因为 n%0 是未定义的行为。

于 2017-12-07T15:41:48.823 回答