C Primer Plus 里面的一道习题,求指点,到底是我写的是对的,还是网上的答案是对的,如果错了错在哪里?
8.编写一个程序,该程序要求用户输入一个华氏温度。程序以double类型读入温度值,并将它作为一个参数传递给用户提供的函数Temperatures()。
该函数将计算相应的摄氏温度和绝对温度,并以小数点右边有两位数字的精度显示这三种温度。
它应该用每个值所代表的温度刻度来标识这3个值。
下面是将华氏温度转换成摄氏温度的方程:
通常用在科学上的绝对温度的刻度是0代表绝对零,是可能温度的下界。下面是将摄氏温度转换为绝对温度的方程:
Kelvin=Celsius+273.16
Temperatures()函数使用const来创建代表该转换里的3个常量的符号。
main()函数将使用一个循环来允许用户重复地输入温度,当用户输入q或其他非数字值时,循环结束。
自认为自己写的没错,虽然没有按照题意“使用const来创建代表该转换里的3个常量的符号”但用人的正常体温验证是对的,代码如下:
程序代码:# include <stdio.h>
void temperatures(double);
int main(void)
{
double f;
printf("请输入一个华氏温度:");
while((scanf("%lf", &f)) == 1)
{
temperatures(f);
printf("请输入一个华氏温度:");
}
return 0;
}
void temperatures(double f)
{
const double k = 273.16, c = 32.00;
printf("华氏%.2lf度 = 摄氏%.2lf度 = 绝对%.2lf度\n", f, (f-c)*5/9, ((f-c)*5/9)+k);
}
/*
VC6.0下运行结果:
-------------------------------------------
请输入一个华氏温度:98.6
华氏98.60度 = 摄氏37.00度 = 绝对310.16度
请输入一个华氏温度:f
Press any key to continue
-------------------------------------------
*/
网上的答案,很多都是像下面这样,个人认为他没有把华氏转为摄氏,用人的正常体温实验一下结果不是题目想要的
程序代码:#include<stdio.h>
void Temperatures(double);
int main(void)
{
double Fahrenheit;
printf("Please input the Fahrenheit:");
while(scanf("%lf",&Fahrenheit) == 1) //scanf的返回值代表成功输入的变量的数目,非数字不会被成功输入
{
Temperatures(Fahrenheit);
printf("Please input the Fahrenheit:");
}
printf("end\n");
return(0);
}
void Temperatures(double Fahrenheit)
{
const double a=1.8,b=32.0,c=273.16;
printf("Fahrenheit = %lf\t",Fahrenheit);
printf("Celsius = %lf\t",a * Fahrenheit + b);
printf("Kelvin = %lf\n",a * Fahrenheit + b + c);
}
/*
VC6.0下运行结果:
-----------------------------------
Please input the Fahrenheit:98.6
Fahrenheit = 98.600000 Celsius = 209.480000 Kelvin = 482.640000
Please input the Fahrenheit:k
end
-----------------------------------
*/




