I needed to write a function that gives 1 if the number written in the terminal is a perfect number or zero if not. I wrote this code and I can't understand what's wrong, can somebody help me? (I just learned functions).
#include <stdio.h>
int PerfectNumber(int n){
int sum = 0;
for (int i = 0; i < n; i ){
if(n % i == 0 && i != 0){
sum = sum i;
}
}
if (sum == n){
return 1;
} else {
return 0;
}
}
int main(){
printf("Inform a number:\n");
int n;
scanf(" %d", &n);
int result = PerfectNumber(n);
if(result == 1){
printf("This is a perfect number!\n");
} else {
printf("This is not a perfect number!\n");
}
return 0;
}
CodePudding user response:
This will fix it:
int PerfectNumber(int n) {
int sum = 0;
for (int i = 1; i < n; i ) {
if (n % i == 0) {
sum = i;
}
}
return sum == n;
}
The problem was that the loop was starting at zero. The loop body checked for it, but only after first using it in a %
operation, so it didn't avoid any divide-by-zero exception. The solution is to simply start the loop at 1, which eliminates the need for any such test in the loop body.