2016-02-05 104 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'会更传统一些;零不起任何作用。 –