You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

3×3二维数组打印格式异常求助:输出行仅显示2组元素

问题分析与修复

核心问题

你的代码存在两个关键错误:

  • 换行逻辑颠倒:if(count % 3) 表示当count除以3有余数时换行,也就是count=1、2、4、5...时都会换行,导致每行只打印2组元素就换行。
  • 数组索引未更新:循环中i和j始终保持初始值0,只会反复覆盖matrixA[0][0]和matrixB[0][0],根本没填满整个3×3二维数组。

修正后的代码

#include <stdio.h>
#include <stdlib.h>

int main(){
  
  int count = 0;
  int matrixA [3][3];
  int matrixB [3][3];
  FILE *fptr;
  int i = 0;
  int j = 0;
  
  fptr = fopen("Matrices.txt","r");
  if(fptr == NULL){
    printf("Error! File cannot be opened");
    exit(1);
  }
  
  // 遍历3×3的数组索引,确保填满两个矩阵
  while(i < 3){
    j = 0;
    while(j < 3){
      // 每次读取两个整数,分别存入matrixA和matrixB的对应位置
      if(2 != fscanf(fptr, "%d%d", &matrixA[i][j], &matrixB[i][j])){
        printf("文件数据不足!");
        fclose(fptr);
        exit(1);
      }
      count++;
      printf("%d %d ", matrixA[i][j], matrixB[i][j]);
      // 当count是3的倍数时换行,实现每行3组元素
      if(count % 3 == 0){
        printf("\n");
      }
      j++;
    }
    i++;
  }

  fclose(fptr);
  return 0;
}

关键修改说明

  1. 调整换行条件为if(count % 3 == 0),只有当打印满3组元素时才换行,符合预期格式。
  2. 改用嵌套循环遍历i和j的索引,确保两个3×3数组的每个位置都被正确填充,而不是只覆盖第一个元素。
  3. 增加了读取失败的判断,避免文件数据不足时出现异常。

内容的提问来源于stack exchange,提问作者Necro Lord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:25:23