我正在寻找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 );}
}
程序在终端中运行,但问题是我只得到第一次温度转换的答案,而不是第二次温度转换的答案(第二次与第一次温度转换相同)。我的问题是为什么第二个答案没有被确定,以及我如何解决它?
答案 0 :(得分:2)
你在分店里不止一次回来。因此,只执行第一个return
语句。
您无法从函数返回几个整数。但是您可以分配一个输出参数数组。我愿意(为什么不是switch/case
陈述?):
void tempConvert(float inTemp, char ch, float results[2])
{
switch(ch)
{
case 'c':
results[0] = ( (5.0/9.0) * (inTemp - 32.0) );
results[1] = ( inTemp + 273.15 );
break;
case 'f':
results[0] = ( ((9.0/5.0) * inTemp ) + 32.0 );
results[1] = ( (5.0/9.0) * (inTemp + 459.67 ) );
break;
case 'k':
results[0] = ( inTemp - 273.15 );
results[1] = ( ((9.0/5.0) * inTemp ) - 459.67 );
break;
default:
results[0] = results[1] = 0; // kind of error code
}
}
这样称呼:
float convert_temp[2]
tempConvert(temp, my_char, convert_temp);
if (my_char == 'c')
printf("The Fahrenheit equivalent is %5.2f degrees\n"
"The Kelvin equivalent is %5.2f degrees\n",
convert_temp[0],convert_temp[1]);