更改 C 中 switch 语句的代码?

标签 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
}

关于更改 C 中 switch 语句的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22791635/

相关文章:

C预处理器宏可以生成函数吗?

c - 在C中将数据转换为7位而不是1字节

c - 发出宏来打印整数的大小和范围

c - 套接字事务未通过

我可以在不关闭 fd 的情况下关闭 FILE 吗?

c - 将可变参数列表传递给子函数

c - while 中的 EOF 跳出范围

c - 什么是 "Syntax of Expression"

c - C语言软件设计实践

Curl 内存缓冲区大小太小