C PRIMER PLUS(第六版编程练习)12.9编程练习_3题

/*
重新设计编程练习2,要求只使用自动变量。该程序提供的用户界面不变,即提示用户输入模式等。但是,函数调用要作相应变化。
*/
//main()
#include  
#include "pe12-2a.h" 
int main(void)
{
	int mode;
	float distance;
	float consumed;
	float* p1;
	float* p2;
	p1 = &distance;
	p2 = &consumed;

	printf("Enter 0 for metric mode, 1 for US mode:\n");
	scanf("%d", &mode);
	while (mode >= 0)
	{
		mode = set_mode(mode);
		get_info(p1,p2,mode);
		show_info(p1,p2,mode);
		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
#pragma once
int set_mode(int n);
void get_info(float *distance,float* consumed,int mode);
void show_info(float* distance, float* consumed, int mode);

//pe12-2a.c

int set_mode(int n)
{
	int mode;
	switch (n)
	{
	case 0: //公制
		mode = 0;
		break;
	case 1://美制
		mode = 1;
		break;
	case -1:
		break;
	default:
		printf("Invalid mode specified. Mode 1( US) used.\n");
		mode = 1;
		break;
	}
	return mode;
}
void get_info(float* distance, float* consumed, int mode)
{
	switch (mode)
	{
	case 0:
		printf("Enter distance traveled in kilometers: \n");
		scanf("%f", distance);
		printf("Enter fuel consumed in liters:\n");
		scanf("%f", consumed);
		break;
	case 1:
		printf("Enter distance traveled in miles:\n");
		scanf("%f", distance);
		printf("Enter fuel consumed in gallons: \n");
		scanf("%f", consumed);
	}
}
void show_info(float* distance, float* consumed, int mode)
{
	float fuel_con = 0;
	switch (mode)
	{
	case 0:
		fuel_con = *consumed / (*distance / 100);
		printf("Fuel consumption is %.2f liters per 100 km.\n", fuel_con);
		break;
	case 1:
		fuel_con = *distance / *consumed;
		printf("Fuel consumption is %.2f miles per gallon.\n", fuel_con);
		break;
	}
}

你可能感兴趣的:(c语言)