我不明白这个程序,我不明白为什么当程序需要用户输入时,数字被初始化为1。 这就是我所理解的计划,显然是错误的:为什么在这个程序中的错误C++?
你走进阶乘数,让我说,进入6,它进入while循环,因为6是大于1 现在factorial
为1,number
是6,6 * 1 = 6
。然后,所以factorial
是5,但我得到720作为输出。
我不认为我明白while循环
#include <iostream>
using namespace std;
int main()
{
// declaration of the variables
int factorial, number;
// initialization of the variables
factorial = 1;
number = 1;
// Prompt the user to enter the upper limit of integers
cout << "Please enter the number of the factorial";
cin >> number;
// using the while loop find out the factorial
while (number > 1)
{
factorial = factorial * number;
number = number - 1;
}
cout << "The factorial is " << factorial;
}
或者使用查表,这允许O(1)复杂性(与O(n)复杂性相反)。这是一个查找表实现的例子:https://gist.github.com/1578501。 – 2012-01-08 14:18:55
如果输入域是无限的,查找表并不能解决问题:)但是,我知道如何使用查找表,并且当您已经知道输入域时它会更好。 – m0skit0 2012-01-08 14:20:08