我已创建此程序将华氏温度转换为摄氏温度,反之亦然现在我想将此if语句转换为switch语句,有人可以帮我完成该任务。
int main(void) {
char condition; // Declare a variable.
float celsius, fahrenheit, temp;
printf("Enter Temp in either Celsius or Fahrenheit: \n"); scanf("%f", &temp); //Ask user to enter Temp.
printf("What type of conversion you want? (hint: 'C/c' for Celsius or 'F/f' for Fahrenheit) \n"); scanf(" %c", &condition);
if ( condition == 'f' || condition == 'F' ) {
fahrenheit = ( temp * 1.8 ) + 32; //Calculates temp in Fahrenheit.
printf("The temp in Fahrenheit is: %.2f", fahrenheit); //Displays result.
} else if ( condition == 'c' || condition == 'C' ) {
celsius = ( temp - 32 ) / 1.8; //Calculate temp in Celsius.
printf("The temp in Celsius is: %.2f", celsius); //Displays result.
}
}
答案 0 :(得分:1)
switch(condition){
case 'f':case'F':
//block
break;
case 'c':case'C':
//block
break;
default:
//error
}
答案 1 :(得分:0)
switch(condition){
case 'f':
case 'F':
fahrenheit = ( temp * 1.8 ) + 32;
printf("The temp in Fahrenheit is: %.2f", fahrenheit);
break;
case 'c':
case 'C':
celsius = ( temp - 32 ) / 1.8;
printf("The temp in Celsius is: %.2f", celsius);
break;
}
答案 2 :(得分:0)
这样的事情会起作用
switch( condition )
{
case 'c':
case 'C':
fahrenheit = ( temp * 1.8 ) + 32; //Calculates temp in Fahrenheit.
printf("The temp in Fahrenheit is: %.2f", fahrenheit); //Displays result.
break;
case 'f':
case 'F':
celsius = ( temp - 32 ) / 1.8; //Calculate temp in Celsius.
printf("The temp in Celsius is: %.2f", celsius); //Displays result.
}
答案 3 :(得分:0)
试试这个:
switch(condition)
{
case 'f':
case 'F':
fahrenheit = ( temp * 1.8 ) + 32; //Calculates temp in Fahrenheit.
printf("The temp in Fahrenheit is: %.2f", fahrenheit); //Displays result.
break;
case 'c':
case 'C':
celsius = ( temp - 32 ) / 1.8; //Calculate temp in Celsius.
printf("The temp in Celsius is: %.2f", celsius); //Displays result.
break;
default: break;
}
背后的逻辑:控制流程一直持续到检测到break
语句为止。因此,即使condition='f'
,也可以使用' F'将被执行然后打破。 c
和C
的情况也是如此。