Is it possible to know if a number is positive
or negative
or 0
in c language
using only two if conditions
?
If yes, then how? please let me know
Is it possible to know if a number is positive
or negative
or 0
in c language
using only two if conditions
?
If yes, then how? please let me know
Use only two if
s:
if (num <= 0) {
if (num == 0) {
/* num is zero */
} else {
/* num is negative */
}
} else {
/* num is positive */
}
I hope this can solve your problem
#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;
}
If c
is a floating point, the problem becomes interesting.
c
may be
1) > 0
2) < 0
3) = 0
4) "Not-a-Number"
#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");
}
At most, 2 if()
s executed.
Without using classification functions/macros
if (x != x || x == 0.0)) {
if (x != x) puts("NaN")
else puts("zero");
}
else {
if (x < 0.0) puts("< 0" )
else puts("> 0");
}