2012-01-08 30 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
相關問題