【发布时间】:2018-08-10 06:30:43
【问题描述】:
我正在寻找有关 C 程序的帮助。我们的教授向我们展示了一个示例,我们将输入摄氏度或华氏度的温度并将其转换为另一个。我发现它很有趣,并尝试更进一步,添加 Kelvin。
#include <stdio.h>
int main(void)
{
#define MAXCOUNT 4
float tempConvert(float, char);
int count;
char my_char;
float convert_temp, temp;
for(count = 1; count <= MAXCOUNT; count++)
{
printf("\nEnter a temperature: ");
scanf("%f %c", &temp, &my_char);
convert_temp = tempConvert(temp, my_char);
if (my_char == 'c')
printf("The Fahrenheit equivalent is %5.2f degrees\n"
"The Kelvin equivalent is %5.2f degrees\n",
convert_temp,convert_temp);
else if (my_char == 'f')
printf("The Celsius equivalent is %5.2f degrees\n"
"The Kelvin equivalent is %5.2f degrees\n",
convert_temp,convert_temp);
else if (my_char == 'k')
printf("The The Celsius equivalent is %5.2f degrees\n"
"The Fahrenheit equivalent is %5.2f degrees\n",
convert_temp,convert_temp);
}
return 0;
}
float tempConvert(float inTemp, char ch)
{
float c_temp1, c_temp2;
if (ch == 'c'){
return c_temp1 = ( (5.0/9.0) * (inTemp - 32.0) );
return c_temp2 = ( inTemp + 273.15 );}
else if (ch == 'f'){
return c_temp1 = ( ((9.0/5.0) * inTemp ) + 32.0 );
return c_temp2 = ( (5.0/9.0) * (inTemp + 459.67 ) );}
else if (ch == 'k'){
return c_temp1 = ( inTemp - 273.15 );
return c_temp2 = ( ((9.0/5.0) * inTemp ) - 459.67 );}
}
程序在终端中运行,但问题是我只得到第一次温度转换的答案,而不是第二次(第二次与第一次相同)。我的问题是为什么没有确定第二个答案,以及如何解决?
【问题讨论】:
-
printf("The Fahrenheit equivalent is %5.2f degrees\n" "The Kelvin equivalent is %5.2f degrees\n", convert_temp,convert_temp);奇怪的是你打印了两次相同的值,有两个不同的图例。 -
argggh 你给
return打了两次电话。只有第一个被执行。 C 不能返回多个值 -
这将是学习使用调试器单步调试代码的绝佳机会。它可以让您快速轻松地解决这种简单的逻辑错误,并且比您在此处发布所花费的时间更短。调试器可能是程序员拥有的最强大的工具,学习使用它永远不会太早。
-
一个函数只能返回一个值。
-
见How to debug small programs——这是一个非常好的链接。
标签: c function for-loop if-statement temperature