我已经创建了这个程序来将华氏度转换为摄氏度,反之亦然,现在我想将此 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.
}
}
最佳答案
switch(condition){
case 'f':case'F':
//block
break;
case 'c':case'C':
//block
break;
default:
//error
}
关于更改 C 中 switch 语句的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22791635/