【问题标题】:My C program is taking only one input instead of multiple input我的 C 程序只接受一个输入而不是多个输入
【发布时间】:2021-11-24 15:46:36
【问题描述】:

我是初学者,我正在学习 C 编程语言。我正在尝试制作一个包含两个矩阵的程序,该程序将接受输入并显示输出。

我为此编写了一个 C 程序,但它只接受一个输入。接受一次输入后,程序将自动终止。

这是我的 C 代码:

#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(matrix1, rows, columns, 1);
  matrixInput(matrix2, rows, columns, 2);
  
  matrixDisplay(matrix1, row, column, 1);
  matrixDisplay(matrix2, row, column, 2);

  return 0;
}

为什么会这样?我该如何解决这个问题?

【问题讨论】:

  • 打开,注意,你的编译器警告。您调用 matrixInput() 时参数顺序错误。
  • 你不应该永远在不检查结果的情况下使用scanf或其他I/O函数。
  • 非常感谢。我的错。我发现了我的错。现在我的程序可以正常运行了。

标签: c arguments function-call function-declaration


【解决方案1】:
void matrixInput(int rows, int cols, int matrix[rows][cols], int matrixNo)

但你在打电话

  matrixInput(matrix1, rows, columns, 1);

应该是这样的

  matrixInput(rows, columns,matrix1, 1);

【讨论】:

  • 非常感谢。我的错。我发现了我的错。现在我的程序可以正常运行了。
【解决方案2】:

这些调用中的参数顺序

matrixInput(matrix1, rows, columns, 1);
matrixInput(matrix2, rows, columns, 2);

matrixDisplay(matrix1, row, column, 1);
matrixDisplay(matrix2, row, column, 2);

不对应函数参数声明的顺序

void matrixInput(int rows, int cols, int matrix[rows][cols], int matrixNo) {

void matrixDisplay(int rows, int cols, int matrix[rows][cols], int matrixNo) {

此外,在最后两次调用中,使用的标识符中有拼写错误。您需要使用rowscolumns,而不是rowcolumn

您需要编写函数调用,例如

matrixInput(rows, columns, matrix1, 1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多