Reputation: 21
I have to write a program with checks "Perfect Numbers" in a specific range given by the user. I made a user-defined function to check if a particular number is a perfect number. If it is then 1 is returned, if not then 0. And then I use an if statement to print out the perfect number in the main program. The issue I'm getting is a floating point exception error. I have no idea what to do now. I'll be really grateful for some help. :).
#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;
}
}
Upvotes: 0
Views: 71
Reputation: 403
Your for loop in isPerfect function should start from 1, because n%0 is undefined behavior.
Upvotes: 1