0

I don't know how to correct this code to make it right?

https://code.sololearn.com/c7tuFBpdcTr0/?ref=app

2nd Jan 2021, 7:47 PM
TeaserCode
5 Answers
+ 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; }
2nd Jan 2021, 8:36 PM
Jayakrishna 🇼🇳
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; }
2nd Jan 2021, 11:13 PM
Poorna Wijesinghe
Poorna Wijesinghe - avatar
0
Another question: Why is inicialization of variable sum in main function and not in perfect Number() where it is used?
3rd Jan 2021, 4:19 AM
TeaserCode
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.
3rd Jan 2021, 10:34 AM
Jayakrishna 🇼🇳
0
Thanks a lot all of you. I understand it.
4th Jan 2021, 12:48 PM
TeaserCode