2014-04-01 119 views
-1

我已经创建了这个程序将华氏转换为摄氏温度,反之亦然,现在我想将这个if语句转换为switch语句,有人可以帮我完成这个任务。更改C语言中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. 
    } 
} 
+4

帮助你,可能。为你做,不。告诉我们你已经尝试了什么,并解释它是如何工作的。 –

回答

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;  
} 
+3

不需要重复相同的代码两次到案例 –

+0

因为a)你正在为他做他的工作和b)你有冗余的代码。 –

+1

由于@JonathonReinhart说了什么,我想看一个动画独角兽。 – clcto

1
switch(condition){ 
case 'f':case'F': 
    //block 
    break; 
case 'c':case'C': 
    //block 
    break; 
default: 
    //error 
} 
+2

从来没有见过这种格式的多个案件处理相同的... - 你用完新线? ;-) – alk

+0

然而,至少在评论中提及1+,“默认”分支表示“异常”。 – alk

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. 
} 
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 statemen t被检测到。所以即使condition='f','F'的情况下也会执行然后中断。在cC的情况下也是如此。