2012-01-08 27 views
0

我不明白这个程序,我不明白为什么当程序需要用户输入时,数字被初始化为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; 
} 

回答

2

你的程序正常工作。

6! = 6 * 5 * 4 * 3 * 2 = 720. 

顺便说一句,使用这种递归问题的递归。

#include <iostream> 

using namespace std; 

int main() 
{ 

    //declaration of the variabe 
    unsigned int number; 

    //prompt the user to enter the upper limit of integers 
    cout << "Please enter the number of the factorial"; 
    cin >> number; 

    cout << factorial(number); 

    return 0; 
} 

unsigned int factorial(unsigned int n) 
{ 
    if (n <= 1) 
    { 
     return 1; 
    } 
    else 
    { 
     return n * factorial(n-1); 
    } 
} 
+0

或者使用查表,这允许O(1)复杂性(与O(n)复杂性相反)。这是一个查找表实现的例子:https://gist.github.com/1578501。 – 2012-01-08 14:18:55

+0

如果输入域是无限的,查找表并不能解决问题:)但是,我知道如何使用查找表,并且当您已经知道输入域时它会更好。 – m0skit0 2012-01-08 14:20:08

0

首先,它被初始化为1,因为以下几个条件:

Factorial(0) = 1 
Factorial(1) = 1 

因此,如果用户输入一个数小于,你并不需要某些计算,只是输出

1

number的初始任务确实是不必要的。然而,你应该检查输入操作错误:

int factorial = 1; 
int number; 

if (!(std::cin >> number)) 
{ 
    /* error! */ 
    return 1; // i.e. abort the program 
} 

while (number > 1) { /* ... */ } 
2

你在程序中的最后一行缺少一个“<”。它应该是

cout<<"The factorial is "<<factorial; 

当我编译和运行该程序进行此更改后,它正确工作,即计算正确的因子。对于例如阶乘5即5 = 5 * 4 * 3 * 2 * 1 = 120

0

我注意到的是,有一个在您代码中的错误的第一件事:

cout<<"The factorial is " < factorial; 

应该是:

cout<<"The factorial is " << factorial; 

更正这应该修复编译错误。

这段代码的实质是:

  1. 从用户那里得到了一些(int number
  2. 打印打印factorialnumber
相关问题