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

C语言矩阵输入程序仅能接收一次输入后自动终止,该如何解决?

问题产生原因
  • 函数调用参数顺序错误:matrixInput函数定义的参数顺序为行数、列数、矩阵变量、矩阵编号,你在main函数中调用时将矩阵变量放在了第一个参数位置,和定义的参数顺序完全不匹配,函数运行时会读取到错误的行列数值,导致循环提前终止甚至程序直接崩溃,无法完成后续输入。
  • 变量名拼写错误:你在main中定义的行列变量为rows和columns,调用matrixDisplay时误写为row和column,属于未定义变量,会导致编译失败或运行逻辑异常。
修复后的完整代码
#include <stdio.h>

void matrixInput(int rows, int cols, int matrix[rows][cols], int matrixNo) {
  printf("Matrix %d input:\n", matrixNo);

  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("Matrix %d [%d, %d]: ", matrixNo, i + 1, j + 1);
      scanf("%d", &matrix[i][j]);
    }
  }

  printf("\n");
}

void matrixDisplay(int rows, int cols, int matrix[rows][cols], int matrixNo) {
  printf("Matrix %d output:\n", matrixNo);

  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }

  printf("\n");
}

int main() {
  int rows, columns;

  printf("Rows: ");
  scanf("%d", &rows);
  printf("Columns: ");
  scanf("%d", &columns);

  int matrix1[rows][columns], matrix2[rows][columns];

  // 修正参数顺序
  matrixInput(rows, columns, matrix1, 1);
  matrixInput(rows, columns, matrix2, 2);
  
  // 修正参数顺序和变量名拼写
  matrixDisplay(rows, columns, matrix1, 1);
  matrixDisplay(rows, columns, matrix2, 2);

  return 0;
}
修复说明
  • 严格按照函数定义的参数顺序传参,先传行数、列数,再传矩阵变量和矩阵编号
  • 修正了变量名的拼写错误,统一使用定义好的rows和columns作为行列参数传入
  • 修复后程序可以正常完成两个矩阵的输入、输出全流程

内容的提问来源于stack exchange,提问作者Satyajit Roy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:27:04