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; }
7 Answers
+ 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;}
+ 1
Yes is true the f value is reset every time the loop run!!! thanks!!!!
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--;
}
0
You're welcome! :)
0
hello!!! I had modified the code and now it seems it's good.
0
Yes Renato, well done!
- 1
I see you found your answer but I see your code and you can make your code more beautiful by using do while .