簡體   English   中英

為什么 C 程序給出錯誤的 output 為正 integer?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM