簡體   English   中英

如何在不知道列長的情況下用C語言輸入矩陣?

[英]How to input a matrix in C language while not knowing the lengths of columns?

我正在做我的C編程作業,其中我需要創建並輸出七張帶有數組的表格,七張表格中的數字規則如下:

表1:從1開始,顯示1個數,跳過1個數,重復直到100
表2:從2開始,顯示2個數,跳過2個數,重復直到100
表3:從4開始,顯示4個數,跳過4個數,重復直到100
表4:從8開始,顯示8個數字,跳過8個數字,重復直到100
表5:從16開始,顯示16個數字,跳過16個數字,重復直到100
表6:從32開始,顯示32個數,跳過32個數,重復直到100個
表 7:從 64 開始,顯示每一個數,直到 100

我的想法是我可以創建一個大表——我可以將所有元素放入其中,具有單獨的行(表)和列(表中的數字)。

但是這里有一個問題:假設我們只知道數字的規則和表格的數量,那么在不知道元素的數量的情況下,我們如何創建表格呢?


現在我已經得到了每個表的元素——但我現在陷入了這一步:如何將元素插入到有七行和未知列的表中?

我如何獲得元素:

......
  //table1~6
  for(int table_number=1;table_number<=6;table_number++) {
    printf("table%d\n",table_number);
    for(int number=pow(2,table_number-1);number<=100;number+=pow(2,table_number)) {
      printf("%3d\n",number);
      for(int skip=1;skip<pow(2,table_number-1);skip++) {
        if(number+skip>100)break;
        else printf("%3d\n",number+skip);
      }
    }
    printf("\n");
  }
  //table7
  printf("table7\n");
  for(int number=pow(2,7-1);number<=100;number++){
    printf("%3d\n",number);
  }

那么如何以同樣的方式將元素插入到表中呢?

我的想法是我可以創建一個大表——我可以將所有元素放入其中,具有單獨的行(表)和列(表中的數字)。

是的,你可以這樣做。 如果您需要使用數組,這可能是完成任務的最簡單方法。

但是這里有一個問題:假設我們只知道數字的規則和表的數量,那么在不知道元素的數量的情況下,我們如何創建一個表呢?

這些數據實際上足以估計存儲所有數字所需的最大容量。

考慮第一個“表”,它只包含 100 以下的奇數,並且有 50 個。

第二個“表”同樣包含范圍內的一半值。

其他的更短,這樣您就可以計算出准確的長度並分配適當的內存量,或者只使用與之前的數組大小相同的數組並跟蹤實際大小。

同樣,最簡單的方法可能是將所有值初始化為零(一個不應該存在的值),然后用正確的值填充數組,直到這些值不大於 100。打印時,只需在以下情況下停止循環達到最大大小或遇到 0。

請參閱以下示例,了解如何自行實施它。

#include <stdio.h>

int main(void)
{
  enum {
    N_TABLES = 7,
    MAX_VALUE = 100,
    MAX_SIZE = MAX_VALUE / 2   // <-- As noted, we don't need more then that.
  };
  // I'm using a multidimensional array to store all the "tables".
  int table[N_TABLES][MAX_SIZE] = {0};
  //                              ^^^  All the values are set to zero.

  for ( int t = 0; t < N_TABLES; ++t )
  {
    // Using pow (which returns a double) to calculate an integer power of two
    // might be inaccurate and maybe slower.
    unsigned start = 1u << t;

    // Well, don't use this "algorithm" in your assignment. It's unlikely what they
    // want you to do. Just note the use of the array.
    for ( unsigned number = start, i = 0; number <= MAX_VALUE; ++number )
    { //                           ^^^^^ 
      if ( number & start )
      {
        table[t][i] = number;
        ++i;                   // <- The index is incremented only when a new value
                               //    is assigned.
      }
    }
  }
  
  // I'll print the values in a tabular fashion. Just transposed.
  for ( int i = 0; i < MAX_SIZE; ++i )
  {
    for ( int j = 0; j < N_TABLES; ++j )
    {
      if ( table[j][i] != 0 )
        printf("%5d", table[j][i]);
      else
        printf("     ");
    }
    putchar('\n');
  }
}

暫無
暫無

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

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