2016-12-03 60 views
-1

輸出什麼,我得到的是C程序使用不工作

choice1:convert the value of temperature in fahrenheit 
choice2:convert the value of temperature in celsius 
Enter the choice(1,2)1 
enter the value in fahrenheit98.6 

Process returned 0 (0x0) execution time : 7.313 s 
Press any key to continue. 

這裏三元運算符是代碼華氏轉換爲攝氏:

#include <stdio.h> 

int main(void) { 
    //Program to convert fahrenheit and celsius temperature into viceversa 
    int choice; 
    float celsius,fahrenheit; 
    printf("choice1:convert the value of temperature in fahrenheit"); 
    printf("\n choice2:convert the value of temperature in celsius"); 
    printf("\nEnter the choice(1,2)"); 
    scanf("%d",&choice); 
    if(choice==1)//control statements 
    { 
     printf("enter the value in fahrenheit"); 
     scanf("%f",&fahrenheit); 
     celsius=(fahrenheit-32)/1.8?:printf("value in celsius is %f",celsius); 
    } 
    else if(choice==2) 
    { 
     printf("enter the value in celsius"); 
     scanf("%f",&celsius); 
     fahrenheit=(celsius*1.8)+32?:printf("value in fahrenheit is %f",fahrenheit);//ternary operator used here 
    } 
    else 
    { 
     printf("/n wrong option");} 
     return 0; 
    } 
    //ternary operator used here 

有三元運算符邏輯的任何問題我們知道三元運算符的syntac是condition?:expression1:expression2;

+1

你爲什麼使用三元運算符?你可以做你的計算並打印出來。 – shamba

+0

「我們知道...」 - 但**我們**也應該知道何時使用它以及何時不使用它。什麼是_expression_(和「條件」)實際上是在C中,什麼應該在三元運算符中使用,以及何時使用條件語句更好。 _conditional operator_不應該被用來替代'if'。 – Olaf

+0

但據我所知,邏輯並沒有錯,因爲它具有所有的要求,是的,我同意你的意見,因爲我們應該知道在哪裏使用它,甚至我們應該知道替代方法。它不使用需要的時候,但我只是想知道在邏輯確切的語法錯誤,以防萬一,如果你的邏輯中使用三元運算符 –

回答

0

您對條件運算符的使用沒有意義。該printf不會發生,除非轉換的結果爲0。即便如此,celsiusfahrenheit變量都尚未設置,因爲三元沒有完成正在評估,因此他們無論打印垃圾價值,他們初步遏制。

你應該做的任務,結果在不同的報表打印。

celsius=(fahrenheit-32)/1.8; 
printf("value in celsius is %f",celsius); 

... 

fahrenheit=(celsius*1.8)+32; 
printf("value in fahrenheit is %f",fahrenheit); 
+0

是的,即使我想這一個聽起來不錯,但我很喜歡這種情況下,可能會出現一些我怎麼能使用三維運算符的內涵這種程序,但後來是我知道了它我的語法是錯誤的情況下,三元運算符條件是不是確切的事情!謝謝! @dbush –

+0

@saidiwakar很高興能幫到你。如果您覺得它有用,請隨時[接受此答案](http://stackoverflow.com/help/accepted-answer)。 – dbush