C Primer Plus(第六版)12.9 编程练习 第2题

时间:2024-01-22 20:48:33

//pe12-2b.c

#include <stdio.h>
#include "pe12-2a.h"

int main(void)
{
    int mode;
    
    printf("Enter 0 for metric mode, 1 for US mode: ");
    scanf("%d", &mode);
    while (mode >= 0)
    {
        set_mode(mode);
        get_info();
        show_info();
        printf("Enter 0 for metric mode, 1 for US mode");
        printf(" (-1 to quit): ");
        scanf("%d", &mode);
    }
    printf("Done.\n");return 0;
}

//pe12-2a.h
void set_mode(int mode);
void get_info(void);
void show_info(void);

//pe12-2a.c


#include "pe12-2a.h"
#include <stdio.h>

static float distance=0.0;
static float fuel_consumed=0.0;
static int Mode;

void set_mode(int mode)
{     
    if(mode == 1 || mode == 0)//只有输入正确才保存到Mode
        Mode=mode;
}
void get_info(void)

    if(Mode==0)
    { 
        printf("Enter distance traveled in kilometers:");
        scanf("%f",&distance);
        printf("Enter fuel consumed in liters: ");
        scanf("%f",&fuel_consumed);
    }
    else if(Mode==1)
    { 
        printf("Enter distance traveled in miles:");
        scanf("%f",&distance);
        printf("Enter fuel consumed in gallons: ");
        scanf("%f",&fuel_consumed);
    }
}

void show_info(void)

    if(Mode==0) 
        printf("Fuel consumption is %.2f liters per 100 km.\n",fuel_consumed/distance*100);
    else if(Mode==1)
        printf("Fuel consumption is %.1f miles per gallon.\n",distance/fuel_consumed);
}