[英]So,I made this simple C program to give output,so it is correct for positive and zero integer values but it is coming wrong for negative even and odd
[英]Why does C program give wrong output for positive integer?
下面的程序给出了负数和零 integer 的正确结果,但对于正数 integer,它给出了错误的 output:
Enter the value of a : 6
The no is positive
The no is zero
为什么?
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");
}
你必须写
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");
否则,两个 if 语句将独立执行。
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");
对于正数,您将获得两个输出。
你的第二个if
应该是else if
。 当你有一个正数时,第一个条件和else
都会运行。
这是因为您使用if
语句而不遵循else
块。 一旦第一个if
被评估,它仍然评估第二个if
,然后因为如果输入是肯定的那将是 false, else
块将运行,打印错误的 output。
兄弟,你必须使用 else if 因为代码检查第一个检查,即 a>0 是真的,然后它会继续,因为没有 else 存在它继续到下一个 if 块,即 a<0 这是假的所以它去否则条件和打印数字为零。
为了避免它考虑使用 else if 这样只有一个块为真,即 a>0 然后程序退出条件语句
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");
您错过了条件,要使其满意,您必须使用if..else..if
int main()
{
int a;
printf("Enter the value of a : ");
scanf("%d",&a);
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");
}
在您的情况下if
条件失败,则直接打印else
条件下的任何内容请尝试上面的代码,您将得到正确的答案。
int a;
printf("Enter the value of a : ");
scanf("%d",&a);
if(a>0)
printf("The no is positive\n");
else if(a<0)
printf("The no is negative\n");
else
printf("zero");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.