c how to program 习题3.16

发布于2020-04-24 888 热度

运行结果:

C语言代码:

/* c how to program 习题3.16 */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    //分别定义变量:燃油量,里程数,总的燃油量,总的里程数,油耗比,平均油耗比
    float gallon, mile, totalGallon=0, totalMile = 0, average, totalAverage;

    //获取第一次使用的燃油量
    printf("Enter the gallons used (-1 to end): ");
    scanf("%f", &gallon);

    //进入循环,直到输入-1结束
    while (gallon != -1.0){
        totalGallon += gallon; //累加总的燃油量

        //获取行使了的里程数
        printf("Enter the miles driven: ");
        scanf("%f", &mile);
        totalMile += mile; //累加总的里程数

        //计算油耗比,并输出
        average = mile / gallon;
        printf("The miles/gallon for this tank was %f\n\n", average);

        //获取下一次使用的燃油量
        printf("Enter the gallons used (-1 to end): ");
        scanf("%f", &gallon);
    }

    //计算并输出平均的油耗比
    totalAverage = totalMile / totalGallon;
    printf("\nThe overall average miles/gallon was %f\n", totalAverage);

    return 0;
}

记录工作,记录学习,分享知识,分享经验……