为什么C程序为正整数给出错误的输出?

MKS*_*MKS 0 c if-statement

下面的程序为负整数和零整数给出正确的结果,但是对于正整数,它给出错误的输出:

Enter the value of a : 6
The no is positive
The no is zero
Run Code Online (Sandbox Code Playgroud)

为什么?

int main()
{   int a;
    printf("Enter the value of a : ");
    scanf("%d",&a);
    if(a>0)
        printf("The no is positive\n");
    if(a<0)
        printf("The no is negative\n");
    else
       printf("The no is zero\n");
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 7

你必须写

if(a>0)
    printf("The no is positive\n");
else if(a<0)
    printf("The no is negative\n");
else
   printf("The no is zero\n");
Run Code Online (Sandbox Code Playgroud)

否则,两个if语句将独立执行。

if(a>0)
    printf("The no is positive\n");
Run Code Online (Sandbox Code Playgroud)

if(a<0)
    printf("The no is negative\n");
else
   printf("The no is zero\n");
Run Code Online (Sandbox Code Playgroud)

对于正数,您将获得两个输出。