2016-08-26 35 views
-4

解決表達的時候,這裏是我的代碼獲取-2147483648十進制

int OP, NP, first, second, third, blankets, remainder; 

printf("How many people are knitting blanket squares at the beginning of the week?\n"); 
scanf("%d", &OP); 
printf("How many new people are knitting blanket squares each day?\n"); 
scanf("%d", &NP); 

//formula 
first = 1 + NP; 
second = pow(first,7); 
third = OP * second; 

blankets = third/(double)60; 
remainder = third - blankets * 60; 

printf("%d blanket squares will be made this week!\n", third); 
printf("You will be able to make %d blankets and start next week with %d squares.", blankets, remainder); 

這是除了當我進入NP的地方小數(如.5)足夠的身體。當我這樣做的時候,我得到了一個溢出,並且它爲第一個printf輸出值-2147483648。我需要改變數據類型嗎?對不起,一個非常簡單的問題,我很新。

+4

是.5'int'? –

+0

您應該嘗試的第一件事是在讀取它們之後立即顯示'OP'和'NP'的值:'printf(「OP =%d,NP =%d \ n」,OP,NP);' –

+0

@奧利弗·查爾斯沃斯另一種說法:針織人是否有可能被削減一半?當然(閱讀:我希望)不是。 C不會浪費資源來防止調用未定義行爲的無意義輸入。 –

回答

2

用整數進行浮點運算可能會溢出整數。這是可能的,但不太可能。當然,你也會失去精確性。您需要至少使用float進行此計算。

真正的問題

  1. 使用scanf()不正確。
  2. 傳遞一個浮點值到scanf()它期望一個整數。它失敗了,但你不知道,因爲(1)。

使用scanf()這樣會導致不確定的行爲,你的變量NPOP從未初始化。但是你不知道,因爲你沒有檢查scanf()的返回值。

你必須檢查它,這樣

if (scanf("%d", &NP) != 1) { 
    fprintf(stderr, "Error, bad input, expecting an `int'.\n"); 
    // Now, `NP' is not initialized unless it was before calling 
    // `scanf' so you can't continue using `NP' safely from 
    // this point 
} 

這同樣適用於OP

如果你想浮點值(和你做,因爲你在你的問題這麼說)使用

float NP, OP; 
if (scanf("%f", &NP) == 1) ... 
+0

@Zatchary - 如果此答案解決了您的問題,請確保接受其他SO用戶可以看到它已解決。謝謝。 – 4386427