C. Ben C. Ben - 16 days ago 5
C Question

My IF program is incorrect

The problem I am having is the output is always '-1' regardless of what I enter.

The rules I must follow are:
outputs -1 if the input number was less than zero;
outputs 0 if the input number was exactly zero;
outputs 1 if the input number was greater than zero.

Code is below:

#include <stdio.h>
int main ()
{
int number;

printf("please enter a number: ");
scanf("%i", &number);

if("number > 0")
{
printf ("-1");
}
else if ("number == 0")
{
printf("0");
}
else if ("number < 0")
{
printf("1");
}
}

Answer

In these if-else statements

if("number > 0")
{
printf ("-1");
}
else if ("number == 0")
{
printf("0");
}
else if ("number < 0")
{
printf("1");
}

there are used string literals like for example "number > 0" as condition expressions. String literals used in expressions are converted to pointers to their first character and always are unequal to 0. tThus the first condition in the if-else statements yields true.

I think you mean the following

if( number > 0 )
{
printf ( "1");
         ^^^^^ 
}
else if (number == 0)
{
printf("0");
}
else 
{
printf("-1");
       ^^^^^
}
Comments