[英]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.