簡體   English   中英

Pascal的Triangle程序不起作用

[英]Pascal's Triangle program not working

我對C還是很陌生,盡管以前我做過很多Java。 我正在制作一個基本的Pascal的Triangle程序,並且已經花了一個小時的時間試圖使其正常工作。 所有的邏輯對我來說似乎都是正確的,但是我可能會在意識到錯誤之前就死了。 這是程序:

#include <stdio.h>
#include <stdlib.h>
double fact(int num);

int main()
{
    int row_index = 0;
    printf("Enter the row index : ");
    scanf("%d",&row_index);
    printf("\n");
    int i;
    double output1 = 0;
    double output2 = 0;
    double output3 = 0;
    double output4 = 0;
    double output5 = 0;
    int output6 = 0;
    for(i = 0; i <= (row_index + 1); i++)
    {
        output1 = fact(row_index);
        output2 = fact(i);
        output3 = row_index - i;
        output4 = fact(output3);
        output5 = output1 / (output2 * output4);
        output6 = (int)(output5);
        printf("%i ",output6);
    }
    return 0;
}

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
        {
            result = result * i;
        }
    return result;
}

編譯器沒有給我任何錯誤,並且每次我輸入一個數字時,它都會將其作為輸出:

Enter the row index : 6

-2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648

double fact(int num) ,應明確初始化變量result 另外,我建議您將函數的返回值和變量resultint類型。

請參閱(為什么)使用未初始化變量的未定義行為?

乍一看,似乎有幾個問題。

第一:

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
    {
    result = result * i;
    }
    return result;
}

結果未初始化為任何東西。 也許您需要將其初始化為1?

for(i = 0; i <= (row_index + 1); i++)
{
    output2 = fact(i);
    output3 = row_index - i;
    output4 = fact(output3);
    output5 = output1 / (output2 * output4);
}

第一次,我== 0; 這意味着output2最多為0(假設其自動初始化為0)。 如果output2 == 0,則可能未定義output5。 我說可能是因為雙精度數字,實際上可能不完全是0。

暫無
暫無

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

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