簡體   English   中英

為什么這個 c 程序在輸入 0 時沒有結束?

[英]Why does this c program not end when entered 0?

無論我是否輸入 0,它都會不斷詢問整數。 我不知道如何結束它。 如果您能幫助我,我將不勝感激。 謝謝。 由於一些基本錯誤,我編輯了代碼。

#include <stdio.h>

int main() {
  int a=1, integers[100];
  while (integers[a] != 0) {
    for (integers[a]; integers[100]; ++a) {
      printf("Enter the integer: \n");
      scanf("%d", & integers[a]);
    }
  }
  
  return 0;
}

你的循環有一些問題。

  1. for循環的頭部有一些奇怪的東西:初始化部分integers[a]沒有任何效果。 你可以跳過它。

  2. 循環條件integers[100]是錯誤的。 沒有元素integers[100]因為數組索引的允許范圍是0..99 您沒有為integers[100]分配任何值。 您的數組未初始化。 您可能想檢查輸入的值是否為0

  3. 如果你修復了內循環,它基本上會和外循環一樣,使它變得多余。

  4. 您不檢查是否將超過 100 個值讀入數組。

試試這個:

#include <stdio.h>

int main(void) {
  int integers[100];
  int a;
  for (a = 0; a < 100; a++) {
      printf("Enter the integer: \n");
      scanf("%d", &integers[a]);
      // TODO: Check result of scanf!

      if (integers[a] == 0)
          break;
  }
  // Now a holds the number of valid values in the array
  // Elements 0..a-1 are filled with input values.
  
  return 0;
}

在不批評您的代碼的情況下,以下是為什么許多語言提供do/while循環的示例。

int main() {
    int index = 0, integers[ 100 ] = { 0 }; // initialise everything

    do {
        printf( "Enter integer #%d (0 to quit): ", index + 1 );
        scanf( "%d", &integers[ index ] );
    } while( integers[ index ] != 0 && ++index < 100 );

    printf( "Collected %d integers from you.\n", index );

    /* todo: do something with the values */

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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