2016-02-05 216 views
-3

這是我第一次編程,我迷路了。我試圖做這個數學運算,但它不斷出錯,我不確定問題出在哪裏。此外,我不知道如何使所有數字輸出到兩位小數。請幫忙。這是我迄今爲止所提出的。數學運算?

int main(void) { 
    int distance, time, speed, meters, mts_per_mile, sec_per_mile, mts, mps; 
    csis = fopen("csis.txt", "w"); 

    distance = 425.5; 
    time = 7.5; 
    speed = distance/time; 
    mts_per_mile = 1600; 
    sec_per_mile = 3600; 
    mts = distance * mts_per_mile; 
    mps = mts/sec_per_mile; 


    printf("The car going %d miles in %d hours is going at a speed of %d mph.\n", distance, time, speed); 
    fprintf("The car going %d miles in %d hours is going at a speed of %d mph.\n", distance, time, speed); 
    printf("The car has traveled %d meters total, at a rate of %d meters per second.", mts, mps); 
    fprintf("The car has traveled %d meters total, at a rate of %d meters per second.", mts, mps); 
    fclose(csis); 
    return 0; 
} 
+5

那麼,而不是使用'int'變量使用'double'或'float'。這將解決您的問題。 – ameyCU

+0

'int'代表[integer](https://simple.wikipedia.org/wiki/Integer)。 –

+5

你打電話給'fprintf'錯誤 –

回答

1

如果您想使用2個小數位,則需要使用雙精度型或浮點型變量。此外,您忘記提及您的csis變量的類型(即FILE*)。 fprintf()以您錯過的句柄FILE*作爲第一個參數。要在輸出中使用兩位小數,只需在printf()/fprint()中使用%.02f

另見printf()和參考fprintf()

#include <cstdlib> 
#include <cstdio> 

int main(void) { 
    double distance, time, speed, mts_per_mile, sec_per_mile, mts, mps; 
    FILE* csis = fopen("csis.txt", "w"); 

    distance = 425.5; 
    time = 7.5; 
    speed = distance/time; 
    mts_per_mile = 1600; 
    sec_per_mile = 3600; 
    mts = distance * mts_per_mile; 
    mps = mts/sec_per_mile; 

    printf("The car going %.02f miles in %.02f hours is going at a speed of %.02f mph.\n", distance, time, speed); 
    fprintf(csis, "The car going %.02f miles in %.02f hours is going at a speed of %.02f mph.\n", distance, time, speed); 
    printf("The car has traveled %.02f meters total, at a rate of %.02f meters per second.", mts, mps); 
    fprintf(csis, "The car has traveled %.02f meters total, at a rate of %.02f meters per second.", mts, mps); 
    fclose(csis); 
    return 0; 
} 

將輸出:

轎廂去425.50英里在7.50小時在56.73 英里每小時的速度去。該車共計行駛680800.00米,速度爲189.11 米/秒。

+0

這會更傳統使用'%.2f';這個零沒有任何用處 –

1

所有的變量都是int,它只存儲整數值。

425.5將被轉換爲int作爲425(舍入趨向零)。同樣,7.5將被轉換爲7

Diving two int s(425 by 7)也會產生一個整數值,向零舍入,因此產生60

如果你的編譯器有一個int類型無法支持價值超過32767(C標準要求實際上沒有比這更多),然後計算60*1600*3600會溢出。這個結果被稱爲未定義的行爲,一種可能的症狀是「錯誤」。

如果您需要非積分實數值,請使用floatdouble類型的變量。然後更改格式說明符,將它們從%d輸出到%f。要輸出到2位小數,請使用格式%.02f

+0

使用'%.2f'會更傳統一些;零不起任何作用。 –