[英]C++ factorial program
我是这种语言的入门者。这很简单,但我做对了。 需要你的帮助
它应该是这样的:
用户输入数字,例如5 ,结果必须为120 (5 * 4 * 3 * 2 * 1)
这是我的代码:
#include<cstdlib>
#include<iostream>
using namespace std;
int main(){
int num;
int prod=0;
cout<<"Enter a number: ";
cin>>num;
cout<<endl;
if(num<1 || num>10){
cout<<"Please enter a number from 1 to 10 only!";
}
else
{
for(int i=num;i>0;i--){
cout<<i;
if(i-1>0){
cout<<"*";
prod = prod * i;
}
}
cout<<" = "<<prod;
}
cout<<endl<<endl;
system("PAUSE");
}
把prod = 1而不是零,这将解决您的问题
#include<iostream>
#include<string>
using namespace std;
void main()
{
int n;
int fact = 1;
cout << "Enter any positive integer to get the factorial value...\n";
cin >> n;
if (n > 0)
{
for (int i = n; n > 0; n--)
{
cout << fact;
if (n > 0)
cout << "*";
fact = fact * n;
cout << "Factorial of " << n << " is = " << fact << endl;
}
}
else
cout << "fact = 0";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.