This program reads a nonnegative integer then it should compute and print its factorial with while statement.
For example 5! 5*4*3*2*1=120
I get 0 as resoult. Can I get some help please?
#include <iostream>
usingnamespace std;
int main(){
int n;
int x;
cout <<"Please enter an integer(-1 to quit):";
cin >> n;
x=n;
if(n>1){
while(n>=1){
n--;
x=x*n;
}
}
elseif(n==1){
x = 1;
}
elseif(n==0){
x = 0;
}
cout<<"n factorial: "<< x ;
}
Your loop goes one-too-far, ultimately multiplying the result by 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main() {
while (true) {
cout <<"Enter an integer(-1 to quit):";
int n;
cin >> n;
if (n < 0)
break;
int f = 1;
while (n > 1)
f *= n--;
cout << "n factorial: "<< f << '\n';
}
}