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

发布时间:2024年01月16日

//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);
}

文章来源:https://blog.csdn.net/apple_50569014/article/details/135628078
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。