第四章习题第8题-bug疑问

在数第四章结尾的习题遇到了问题,死活找不到以前写的程序的bug所在:

具体就是第8题

环境是Windows下的Dev-C ++ 5.11,Gcc 4.92;

今天写的代码:

#include <stdio.h> 
#define GTOL 3.785
#define MTOK 1.609

int main(void)
{
    float mile,gallon;

    printf("请输入旅行的里程(英里):\n");
    scanf("%f",&mile);
    printf("请输入旅行的耗油(加仑):\n");
    scanf("%f",&gallon);
    printf("行驶耗油是 %.1f 英里/加仑;\n",mile/gallon);
    printf("换算过来是 %.1f 升/百公里。\n",(gallon*GTOL)/(mile*MTOK/100));

    return 0;
}

运行结果:

请输入旅行的里程(英里):
100
请输入旅行的耗油(加仑):
10
行驶耗油是 10.0 英里/加仑;
换算过来是 23.5 升/百公里。

以前写的代码:

//A是3.785,B是1.609,c是里程,d是消耗汽油量;
#include <stdio.h> 
#define A 3.785
int main(void)
{
    const int B = 1.609;
    float c,d;

    printf("请输入旅行的里程(单位英里)和消耗的汽油量(单位加仑):\n");
    scanf("%f%f",&c,&d);
    printf("消耗每加仑汽油行驶的英里数为:%.1f\n",c/d);
    printf("一加仑约3.785升,一英里约1.609千米\n所以百公里要消耗%.1f升汽油",(A*d)/(B*c/100));

    return 0;
}

运行结果:

请输入旅行的里程(单位英里)和消耗的汽油量(单位加仑):
100
10
消耗每加仑汽油行驶的英里数为:10.0
一加仑约3.785升,一英里约1.609千米
所以百公里要消耗37.9升汽油

博客主写的:

/************************************************************************/
/* practice 8                                                                     */
/************************************************************************/
#define KM_PER_MILE (1.609)
#define PINT_PER_GALLON (3.785)
void p4_8(void)
{
    float driven_distance = 0.0;
    float gas_consumption = 0.0;
    float pint_per_hundred_km = 0.0;
    float mile_per_gallon = 0.0;
    printf("How much distance have you traveled in kilometer:");
    scanf_s("%f", &driven_distance);
    getchar();

    printf("How much gas have you used in pint:");
    scanf_s("%f", &gas_consumption);
    getchar();

    pint_per_hundred_km = gas_consumption / driven_distance * 100;
    mile_per_gallon = (driven_distance / KM_PER_MILE) / (gas_consumption / PINT_PER_GALLON);

    printf("Fuel consumptions:%f pint/100km or %f mile/gallon\n", pint_per_hundred_km, mile_per_gallon);
}

int main(int argc, char **argv)
{
    p4_8();

    getchar();
}

运行结果:

How much distance have you traveled in kilometer:100
How much gas have you used in pint:10
Fuel consumptions:10.000000 pint/100km or 23.523928 mile/gallon

猜你喜欢

转载自blog.csdn.net/weixin_42029360/article/details/80638347