【发布时间】:2017-09-30 06:37:56
【问题描述】:
#include<stdlib.h>
#include<stdio.h>
int main() {
FILE* file = fopen ("fourth.txt", "r");
int i = 0;
int rows=0;
int rows2=0;
int columns=0;
int counter=0;
int length=0;
int multiply=0;
fscanf (file, "%d", &i);
rows=i;
printf("the rows are %d\n", i);
int matrix[rows][rows];
length=rows*rows;
if (rows<=0) {
printf("error, this file cannot be processed");
return 0;
}
do
{
if (fscanf(file, "%d", &i)==1) {
if (counter<length) {
matrix[rows2][columns]=i;
counter++;
columns++;
if (columns==rows) {
rows2++;
columns=0;
}
}
multiply=i;
}
} while (!feof(file));
fclose (file);
for ( int c = 0; c < rows; c++ ) {
for ( int j = 0; j < rows; j++ ) {
printf("matrix[%d][%d] = %d\n", c,j, matrix[c][j] );
}
}
printf("the multiply is %d", multiply);
我正在尝试创建一个矩阵指数(换句话说,矩阵乘法)。然而,在我执行实际的数学过程之前,我必须从 txt 文件中读取数字作为输入并将它们存储在二维数组中。以上是到目前为止我从代码中获得的内容,但是,我很难将数字实际输入到数组中,因为当我在最后测试我的二维数组时,我得到了奇怪的结果。
例如: 1. 输入:
3
123
456
789
2
3 代表行数,这与这个特定二维数组的列数相同,因为矩阵是正方形的,意思是 所有行和列都相同。
2 代表指数,即我必须将原始矩阵与自身相乘的次数。
但是我的输出是
矩阵[0][0] = 123
矩阵[0][1] = 456,
矩阵[0][2] = 789
矩阵[1][0] = 2
矩阵[1][1] = 4214800
矩阵[1][2] = 0
矩阵[2][0] = 3
矩阵[2][1] = 0
矩阵[2][2] = 0
预期输出必须是:
123
456
789
在二维数组中
有什么原因吗?
另外,我将如何修改代码,因此无论 txt 文件中关于不同行和列的输入是什么,我仍然可以格式化正确的二维数组。谢谢
【问题讨论】:
-
123 是一个数字 - 如果您想将其读取为 3 个数字 - 最好在它们之间添加空格 1 2 3
-
或
if (fscanf(file, "%d", &i)==1) {(不包括负数时)-->if (fscanf(file, "%1d", &i)==1) { -
注意:
if (rows<=0) {测试最好在int matrix[rows][rows];之前编码 -
do { if (fscanf(file, "%d", &i)==1) { ... } while (!feof(file));处于非数字输入的无限循环中。 -
要一次读取一个数字,使用
"%d",使用fscanf(file, "%1d", &i)(加1)