gpt4 book ai didi

c - 读取包含负数的矩阵并存储在数组中。 C

转载 作者:行者123 更新时间:2023-11-30 21:05:44 24 4
gpt4 key购买 nike

我需要读取一个包含矩阵的文件。问题是如果矩阵也包含负数怎么办?

2  -20   1
5 -4 -312
10 4 -3

假设该文件包含此内容。我如何读取它并将其存储在 int 中大批?语言是 C。感谢您的帮助。

最佳答案

负数的处理方式与正数相同。 documentation for fscanf明确这样说:

d Decimal integer Any number of decimal digits (0-9), optionally preceded by a sign (+ or -).
(http://www.cplusplus.com/reference/cstdio/fscanf/?kw=fscanf)

因此,如果您在 fscanf 中使用 %d,则无需对负数执行任何特殊操作。

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

int main(void)
{
int matrix[3][3];
int row,col;
FILE *read_file;

read_file = fopen ("matrix.txt", "r");
for (row=0; row<3; row++)
{
for (col=0; col<3; col++)
{
if (fscanf (read_file, "%d", &matrix[row][col]) < 1)
{
printf ("unexpected end of file or other error\n");
exit(-1);
}
}
}
fclose (read_file);

for (row=0; row<3; row++)
{
for (col=0; col<3; col++)
{
printf ("%4d ", matrix[row][col]);
}
printf ("\n");
}

return 0;
}

结果:

   2  -20    1 
5 -4 -312
10 4 -3

关于c - 读取包含负数的矩阵并存储在数组中。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com