C Primer Plus中的一个练习题

第五章的最后一个练习题,5-8.

要求:

/*
输入一个华氏温度。以double类型读入温度值,并将它作为一个参数传递给用户提供的函数Temperatures()。
该函数将计算对应的摄氏温度和绝对温度,并以小数点右边有两位数字的精度显示这三种温度。
它应该用每个值所代表的温度刻度来标识这三个值。
Celsius = 1.8 * Fahrenheit + 32.0
Kelvin = Celsius + 273.16
*/

 最开始,我写了如下的代码:

先用gets(),获取输入字符串,再比较第一个字符是否是数字来判断输入是否合法,再用sscanf()函数读取输入字符串中的数字。

#include <stdio.h>

void Temperatures(double Fahrenheit);

int main(void)
{
	double tmp;

	char str[20];

	printf("Enter a temperature in Fahrenheit:\n");
	gets(str);

	while (str[0] >= '0' && str[0] <= '9')
	{
		sscanf(str,"%lf", &tmp);
		Temperatures(tmp);
		printf("Enter a temperature in Fahrenheit:\n");
		gets(str);
	}

	return 0;
}

void Temperatures(double Fahrenheit)
{
	float Celsius, Kelvin;
	Celsius = 1.8 * Fahrenheit + 32.0;
	Kelvin = Celsius + 273.16;
	printf("%.2f  %.2f  %.2f", Fahrenheit, Celsius, Kelvin);

}

 

 

后来发现,如过利用scanf()的返回值作为判断,可以简化代码。

scanf()函数的返回值是成功读入的项目的个数,假如没有读取任何项目,则返回值为0。

简化后的代码:

#include <stdio.h>
void Temperatures(double Fahrenheit);
int main(void)
{
	double tmp;

	printf("Enter a temperature in Fahrenheit:\n");
	while (scanf("%lf", &tmp))
	{
		Temperatures(tmp);
		printf("Enter a temperature in Fahrenheit:\n");
	}
	return 0;
}

void Temperatures(double Fahrenheit)
{
	float Celsius, Kelvin;
	Celsius = 1.8 * Fahrenheit + 32.0;
	Kelvin = Celsius + 273.16;
	printf("%.2f  %.2f  %.2f", Fahrenheit, Celsius, Kelvin);

}

 

posted @ 2014-06-24 15:40  liuxia_hust  阅读(334)  评论(0编辑  收藏  举报