簡體   English   中英

為什么此程序C ++中出現錯誤?

[英]why is the error in this program c++?

我不懂這個程序,我不明白為什么當程序需要用戶輸入時數字被初始化為1。 這就是我對程序的理解,這顯然是錯誤的:

您輸入階乘數,讓我輸入6,因為6大於1,所以進入while循環。現在factorial為1, number6 * 1 = 6 然后factorial 6 - 1 = 5 ,因此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;
}

您的程序正常運行。

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);
    }
}

您在程序的最后一行中缺少“ <”。 它應該是

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

進行更改並編譯並運行程序后,它可以為我正確運行,即計算正確的階乘。 例如5的階乘,即5!= 5 * 4 * 3 * 2 * 1 = 120

的初始分配number確實是不必要的。 但是,您應該檢查輸入操作是否有錯誤:

int factorial = 1;
int number;

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

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

首先,由於以下條件,將其初始化為1:

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

因此,如果用戶輸入的數字小於2 ,則無需進行任何計算,只需輸出1

我注意到的第一件事是您的代碼中存在錯誤:

cout<<"The factorial is " < factorial;

應該:

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

更正此錯誤將解決編譯錯誤。

該代碼的本質是:

  1. 從用戶獲取一個數字( int number
  2. 打印打印階乘number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM