簡體   English   中英

打印無符號數組並退出循環

[英]printing unsigned array and exiting the loop

總結

我希望能夠編寫一個可以存儲10值的函數。 我應該能夠以0退出循環,而無需將0存儲到數組中。 我應該能夠重新輸入數組並繼續存儲直到得到10值。

問題

  1. 我開始寫一些簡單的東西,但是當我存儲5值時,它將先打印5值,然后再打印一些隨機數。 這是為什么?

  2. 以及如何在數組不存儲0情況下退出循環?

我對這些東西還很陌生,所以希望我在這里正確地遵循了規則。

代碼

#include <stdio.h>

int main(void)
{
    int arrayTable[9] = {0};
    int i;

    for (i=0; i<10; i++)
    {
        printf("Enter Measurement #%i (or 0): ", i+1);
        scanf("%d", &arrayTable[i]);
        if (arrayTable[i] == 0)
        {
            break;
        }
    }

    for (int i=0; i<10; i++)
    {
        printf("%d\n", arrayTable[i]);
    }

    return 0;
}
#include <stdio.h>

#define ArraySize 10

int main(void){
    unsigned v, arrayTable[ArraySize] = {0};
    int n = 0;//number of elements

    while(n < ArraySize){
        printf("Enter Measurement #%i (or 0): ", n + 1);
        if(1 != scanf("%u", &v) || v == 0){//use other variable
            break;
        }
        arrayTable[n++] = v;
    }

    for (int i = 0; i < n; ++i) {
        printf("%u\n", arrayTable[i]);
    }

    return 0;
}

您可能想要這樣:

  ...
  int arrayTable[10] = {0};   // <<< [10] instead of [9]

  ...

  for (i=0; i<10; i++)
  {
      if (arrayTable[i] == 0) // <<< add this
        break;                // <<<

      printf("%d\n", arrayTable[i]);
  }
  ...

只要您想從數組中丟棄0,然后使用一個臨時變量,輸入它,檢查它是否為非零,如果是,則將其存儲到數組的元素中;如果為零,則退出循環:

#include <stdio.h>

int main(void)
{

    int arrayTable[10] = {0};
    int iValue         = 0;
    int i              = 0;

    while(i < 10)
    {
         printf("Enter Measurement #%i (or 0): ", i+1);
         scanf("%d", &iValue); // input iValue

         if (!iValue) // if iValue is zero then exit loop without affecting array with this value
            break;
         else
        {
            arrayTable[i] = iValue; // if the value is non-zero store it in array and continue
            i++;
        }
    }

    for (int i = 0; i < 10; i++)
    {
        printf("%d\n", arrayTable[i]);
    }

    return 0;
}

暫無
暫無

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

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