簡體   English   中英

我的階乘和冪函數在不應該且不知道如何解決的情況下輸出數百萬的數字(在c中)

[英]My factorial and power functions output a number in the millions when it shouldn't and I don't know how to fix it(in c)

我正在嘗試編寫一種計算器程序,除我的階乘和冪函數外,其他所有函數都可以使用。 無論數字多么小,它們都會輸出數百萬的數字,我看不出代碼有問題。 (我最近才剛開始學習C,所以假設我的知識范圍就是這段代碼中的全部內容)

int iFactorial(num1){//needs help returns a number in the millions no matter what

    int i, factorial=1;
    printf("Enter a positive number: ");
    scanf("%d", &num1);
    for(i=1; i<=num1; i++)
            factorial*=i;
            printf("The factorial is %i", &factorial);
    return 0;

}
int fPower(num1,num2){//needs help, same as above
    int i, number = 1;
    printf("Enter the number you want to raise to a power: \n");
    scanf("%d", &num1);
    printf("Enter the exponent: ");
    scanf("%d", &num2);

    for(i=0; i<num2; i++)
        number*=num1;
        printf("%d to the %d equals %d", &num1, &num2, &number);
    return 0;  
}

您在打印語句中使用&來打印所用變量的地址。 更正其各自功能中的語句,如下所示:

printf("The factorial is %i", factorial);

printf("%d to the %d equals %d", num1, num2, number);

您的階乘和冪情況的printf格式不正確,您正在通過指針傳遞參數; 您需要按價值傳遞它們。

之后,您會很快意識到在階乘和冪情況下int類型將會溢出。 一般而言,一個int最多只能包含7! 在真正可移植的C ++中。 考慮使用unsigned long long ,這將使您的值最高為21! 在格式化程序中使用"%ull"表示unsigned long long

最后,將類型顯式傳遞給C語言中的函數:自C99以來,顯式禁止使用您的樣式。

您使用了錯誤的格式說明printf打印結果,而你不及格要打印的實際值:

printf("The factorial is %i", &factorial);

您傳遞的是factorial的地址而不是其值,因此它將打印它。 只需直接傳遞結果而不是其地址即可:

printf("The factorial is %i", factorial);

暫無
暫無

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

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