2014-02-26 53 views
-9

是否有可能知道,如果僅使用兩個if conditions一些是c languagepositivenegative0如何知道一個數字是正或負或0

如果是,那麼如何?請讓我知道

+5

你是認真的?你嘗試了什麼? – unwind

+0

作業,我想象? – Mawg

+1

是的我是,我嘗試過與terinary運營商,開關的情況下,但每個地方它是採取3個條件 – user2753523

回答

3

僅使用兩個if S:

if (num <= 0) { 
     if (num == 0) { 
      /* num is zero */ 
     } else { 
      /* num is negative */ 
     } 
} else { 
    /* num is positive */ 
} 
+3

嗯..如果'num'爲零,你的代碼首先會說它是零,然後說它是負數,然後是正數。不是嗎? – devnull

+0

你確定你不錯嗎? –

+0

@devnull你說得對,'其他'錯過了。 –

3

我希望這能解決你的問題

#include <stdio.h> 
int main() 
{ 
    float num; 
    printf("Enter a number: "); 
    scanf("%f",&num); // Take input from user 
    if (num<=0)   // if Number is >= 0 
    {      
     if (num==0)  // if number is equal to zero 
      printf("You entered zero."); 
     else    // if number is > 0 
      printf("%.2f is negative.",num); 
    } 
    else    // if number is < 0 
     printf("%.2f is positive.",num); 
    return 0; 
} 
0

如果c是浮點,問題就變得有趣了。

c可以
1)> 0
2) 3)= 0
4) 「不是一個號碼」

#include <math.h> 
... 
int classification = fpclassify(x); 
if (classification == FP_NAN || classification == FP_ZERO)) { 
    if (classification == FP_NAN) puts("NaN") 
    else puts("zero"); 
} 
else { 
    if (signbit(x)) puts("< 0") 
    else puts("> 0"); 
} 

至多,2個if()小號執行。

不使用分類功能/宏

if (x != x || x == 0.0)) { 
    if (x != x) puts("NaN") 
    else puts("zero"); 
} 
else { 
    if (x < 0.0) puts("< 0") 
    else puts("> 0"); 
} 
相關問題