0

Hello!!! Some one can tell me what's going wrong for this code?I try to calculate the factorial of a number

#include <iostream> using namespace std; int main() { long long int num,f,i; i=1; cin>> num; while (num<0){cout<<"please another number"<<endl; cin>>num;} if(num==0){cout<<"1"<<endl;} else (num>0){while(i<num){f=num(num-i);i++;}} return 0; }

10th Apr 2021, 6:01 PM
Renato Elezi
Renato Elezi - avatar
7 Antworten
+ 2
#include <iostream> using namespace std; int main() { long long int n,i,f; i=1; f=1; cout <<"pleas enter a number"<<endl; cin >>n; if(n<0){cout <<"pleas enter a positiv number"<<endl;} cin >>n; if(n>=0){if(n>0){while(i<=n){f*=i;i++;}cout <<"result is:"<<endl;cout <<f;}} else{cout <<"result is:"<<endl;cout <<1;} return 0;}
11th Apr 2021, 11:24 AM
Renato Elezi
Renato Elezi - avatar
+ 1
Yes is true the f value is reset every time the loop run!!! thanks!!!!
10th Apr 2021, 6:46 PM
Renato Elezi
Renato Elezi - avatar
0
The algorithm seems wrong, even if the syntax was right. (I'm not an expert with C++ but num(num-i) looks wrong) Trying to calculate f = num*(num-i) will reset f's value every time in the loop. You need to protect the result, not reset it. Also you need to keep your loop until i greater than the num. Initialize f = 1, then multiply it with i each time. Like; f = 1, i = 1; while(i<=num){ f *= i; i++; } Or like; while(num){ i *= num--; }
10th Apr 2021, 6:34 PM
ogoxu
ogoxu - avatar
0
You're welcome! :)
10th Apr 2021, 6:48 PM
ogoxu
ogoxu - avatar
0
hello!!! I had modified the code and now it seems it's good.
11th Apr 2021, 11:24 AM
Renato Elezi
Renato Elezi - avatar
0
Yes Renato, well done!
11th Apr 2021, 2:43 PM
ogoxu
ogoxu - avatar
- 1
I see you found your answer but I see your code and you can make your code more beautiful by using do while .
12th Apr 2021, 5:43 PM
Saeed
Saeed - avatar