0
I don't know how to correct this code to make it right?
5 Réponses
+ 1
You need lot corrections.. You are calling perfectNum function only but calculation done in perfectNumber function. So Fisrt call perfectNumber calculation function then call deside function perfectNum. And no need switch case and also you are not using it properly..
I arranged it to work code but it can also be improved i think.. Hope it helps..
//Is it perfect number?
#include <iostream>
using namespace std;
int perfectNumber(int &n,int &sum){
for(int i = 1; i < n; i++){
if(n % i == 0)
sum += i;}
//cout << i << " ";
return sum;
}
bool perfectNum(int n,int sum){
if(sum == n)
return true;
else
return false;
}
int main() {
int n = 28;
int sum=0;
cin >> n;
cout << perfectNumber(n, sum)<<"\n"<< perfectNum(n,sum);
return 0;
}
0
//Is it perfect number?
#include <iostream>
using namespace std;
int perfectNumber(int &n, int &sum){
for(int i = 1; i < n; i++){
if(n % i == 0)
sum += i;
}
return sum;
}
bool perfectNum(int n, int sum){
if(sum == n)
return true;
else
return false;
}
int main() {
int n = 0;
int sum = 0;
cin >> n; // user input
cout << "Sum = ";
cout << perfectNumber(n,sum) << "\n";
cout << "True (1) or False (0) : ";
cout << perfectNum(n,sum);
return 0;
}
0
Another question:
Why is inicialization of variable sum in main function and not in perfect Number() where it is used?
0
Yes. You can. Like this. It's works perfectly...
int perfectNumber(int n){
int sum = 0;
for(int i = 1; i < n; i++){
if(n % i == 0)
sum += i;}
return sum;
}
And assign return value in main like this...
int sum=perfectNumber(n);
Here in function variable and variable in main are different once. Changes in one will not reflect on another. But in your original code you are passing variable address as &sum so changes in sum variable in perfectNumber function will reflect in calling function main variable. So without returning value also works same.
0
Thanks a lot all of you. I understand it.