[英]Change the code for switch statement in C?
我已经创建了这个程序来将华氏度转换为摄氏度,反之亦然,现在我想将此 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
}
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;
}
像这样的东西会起作用
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.
}
尝试这个:
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
的情况下也会发生同样的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.