2014-10-17 17 views
-4

好吧,夥計們,我對此有一段時間。目前,我正在研究C語言中的if語句(很明顯,編程介紹),我似乎無法得到if else語句正確的語法。我瀏覽過網頁,但沒有找到任何相關答案。我目前收到的錯誤是: | 47 | error:expected')'數字常量之前|麻煩,如果C語言中的陳述與計算相結合

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 


float p(float r, float v) 
{ 
    return (v*v)/(r); 

    } 

int main() 
{ 


    float r, v, answer;     //The user input and print for title of values 
    puts("Enter Voltage:"); 
    scanf("%f", &r); 
    puts("Enter Resistance:"); 
    scanf("%f", &v); 
    answer = p(v, r); 
    printf("Pd=%.9f\n", answer); 

    return 0; 


scanf("%f", answer); 
if (answer >= 0.25) 
{ 


     /* if condition is true then print the following */ 
     printf("WARNING: Power Dissipation should not exceed 1/4 Watt\n"); 
} 




else if ((answer) 0.25 < =<0.5 >) 
     { 

     printf("WARNING: Power Dissipation should not exceed 1/2 Watt\n"); 

} 

scanf("%f", &answer); 
if ((answer 0.5< & 1 >=< 1) 
     printf("WARNING: Power Dissipation should not exceed 1 Watt"); 



} 

如果您有空餘時間,請幫忙。

+0

這將有助於縮進代碼。 – hetepeperfan 2014-10-17 20:23:36

+4

你的第二個和第三個'if'語法錯誤。請查看您的課程筆記。 (關於重讀:我甚至無法理解你想要測試的內容......) – usr2564301 2014-10-17 20:23:52

+3

看起來你在你的主體中間有一個'return'。這可能是不對的。 – dohashi 2014-10-17 20:25:09

回答

2

你有很多語法錯誤:

((answer) 0.25 < =<0.5 >) 

無效C.這可能是您的錯誤消息的來源。但後來,你也有

((answer 0.5< & 1 >=< 1) 

這也是無效的C和&AND操作,&&是。這些與if語法無關,它們在您找到它們的任何地方都是無效表達式。

如果你完全清楚你想要用這些語句完成什麼,這可能會有所幫助。但是,一般來說,在開始擔心if陳述之前,您應該重新檢查您的基本C boolean expression syntax

一旦你做到了這一點,在C的if語句的一般形式是:

if(int){statements;} 

int被認爲是false如果是0,並且true如果是別的( C缺少本地布爾類型)。您放入()的任何表達式都必須計算爲整數或者可以隱式轉換爲一個整數。只有當表達式爲true時,纔會評估{}之間的聲明。

+0

這使得事情更清晰,謝謝@! – 2014-10-17 20:32:38

1

這種情況是相當簡單:

if (answer >= 0.25) 

這兩個,但是......

else if ((answer) 0.25 < =<0.5 >) 
if ((answer 0.5< & 1 >=< 1) 

究竟什麼是你想在這些情況下進行測試?

我打算假設(根據後面的打印聲明)您檢查的功率是否超過半瓦或全瓦,在這種情況下,它們與第一種情況類似:

if (answer >= 0.5) 
if (answer >= 1.0) 

SP代碼將被構建爲

if (answer >= 0.25) 
    printf("Warning: power dissipation should not exceed 1/4 watt\n"); 
else if (answer >= 0.5) 
    printf("Warning: power dissipation should not exceed 1/2 watt\n"); 
else if (answer >= 1.0) 
    printf("Warning: power dissipation should not exceed 1 watt\n"); 

除...

如果answer大於或等於1.0,那麼它也越大日等於0.5和0.25;第一個分支將被打印,打印超過四分之一瓦特的警告,當您可能想要打印超過1瓦的警告時。你可能想扭轉測試的順序,像這樣:

if (answer >= 1.0) 
    printf("Warning: power dissipation should not exceed 1 watt\n"); 
else if (answer >= 0.5) 
    printf("Warning: power dissipation should not exceed 1/2 watt\n"); 
else if (answer >= 0.25) 
    printf("Warning: power dissipation should not exceed 1/4 watt\n"); 
else 
    printf("power dissipation does not exceed 1/4 watt\n"); 

所以,如果answer是一樣的東西0.75,你會得到警告了超過一個半瓦;如果它是0.35,你會得到超過四分之一瓦的警告等。

+0

這是,令人興奮的。謝謝@John Bode – 2014-10-18 04:29:40