我必须编写一个程序,在用户给定的特定范围内检查“完美数字”。我做了一个用户定义的函数来检查一个特定的数字是否是一个完美的数字。如果是则返回 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;
}
}
最佳答案
isPerfect 函数中的 for 循环应该从 1 开始,因为 n%0 是未定义的行为。
关于c++ - 使用用户定义的函数查找 '' Perfect Number 时出现浮点异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47698124/