簡體   English   中英

為什么我的C程序最多可以找到21個階乘,而從13個階乘開始產生無效結果?

[英]Why is my C program for finding factorials up to 21 producing invalid results starting at the factorial for 13?

在計算13的階乘時,它開始產生無效的結果。 我已經按照教科書中的書寫方式進行了精確鍵入,但是得到的輸出與書中列出的有所不同。 我的編譯器是Dev C ++,並且其設置為C99標准。 編譯器中是否存在某些設置會導致無符號的long long整數無法正確格式化或沒有合適的最大值? 13歲! 它打印1932053504。

#include <stdio.h>

//prototype for factorial function
unsigned long long int factorial(unsigned int number);

int main(void){
    unsigned int i; //counter for for-loop

    //during each iteration call factorial and print result
    for( i = 0; i <= 21; ++i){
        printf("%u! = %11u\n", i, factorial(i));
    }
}

unsigned long long int factorial(unsigned int number){
    if(number <= 1){
        return 1;
    }
else{ //recursive step
    return(number * factorial(number - 1));
    }
}

我認為您的說明符中有錯字。 我覺得你的意思ll不是11 您要傳遞一個unsigned long longunsigned long long ,所以它需要

printf("%u! = %llu\n", i, factorial(i));

這是打開(並注意)編譯器警告的另一個原因。 我的編譯器立即告訴我問題出在哪里。

test.c:11:35: warning: format specifies type 'unsigned int' but the argument has type 'unsigned long long' [-Wformat]
        printf("%u! = %11u\n", i, factorial(i));
                      ~~~~        ^~~~~~~~~~~~
                      %11llu
1 warning generated.

您得到的答案是未定義行為的結果,但是您的機器是低位字節序的,具有32位整數,13! = 6227020800> 2 ^ 32 = 4294967296,而6227020800%4294967296 = 1932053504可能就是您得到該答案的原因。

暫無
暫無

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

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