iT邦幫忙

0

【資料結構】讀檔相關 12/18更

二維陣列的一維讀入法

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
int main() {
  FILE *f = fopen("new.txt", "r");
  if (f == NULL) {
    printf("no file");
    return -1;
  }
基本的讀入判斷,利用fopen將位置存入f,並判斷檔案是否存在
  int count=0, top = -1, arr[MAX] = {0};
  while (EOF != fscanf(f, "%d", &arr[++top])) {
  }
  fclose(f);
持續讀檔,將讀到的資料放入陣列中,直到沒有資料傳入為止
  count = sqrt(top);
  printf("top=%d\n", top);
  printf("now=%d\n", count);
此時top為矩陣元素總數量,利用math中的sqrt函式取top的開根號,可得邊長(限同邊長矩陣)
  for (int i = 0; i < count; i++) {
    for (int j = 0; j < count; j++) {
      printf("%d ", arr[i * count + j]);
    }
    printf("\n");
  }
}
利用一維的方式印出二維矩陣

其他

待補


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言