gpt4 book ai didi

c 扫描二维数组

转载 作者:行者123 更新时间:2023-11-30 14:49:25 25 4
gpt4 key购买 nike

我对c语言很陌生,遇到了一个问题,我认为与指针有一些关系(可能是错误的)。第一个输入显然是输入的数量,它(当前)也决定了宽度和高度数组。接下来的几个输入应该读取我自己的数组坐标及其值。最后一点我试图打印出数组。输出是非常非常错误的。关于我在扫描部分或打印部分或两者都做错的地方有什么提示吗?

(如果 st_objects 是 5,我的 x_cord 和 y_cord 的最大输入是 4)我只是想将一些值更改为 0 以外的值。首先我需要用 0 值填充数组?

类似于:

0 0 0 2 0

0 2 3 0 0

0 0 0 0 2

0 0 0 1 2

0 0 2 0 3

Ps:输入时使用getchar函数会更好吗?

我的代码是:

 #include <stdio.h>

int main(){
int st_objects;
scanf("%d",&st_objects);

int x_cord;
int y_cord;
int array[st_objects][st_objects];

for(int i = 0; i < st_objects; i++){
scanf("%d",&x_cord);
scanf("%d",&y_cord);
scanf("%d",&array[x_cord][y_cord]);

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

return 0;
}

最佳答案

您的扫描循环仅执行到 st_object 次(在本例中为 5)。所以你只能接受 5 个输入。但如果你看到的话,数组包含 5*5=25 个元素。所以这是一个出错的地方。

接下来,还有更好的方法来扫描数组元素,就像这样

for(int i = 0; i < st_objects; i++)
for(int j = 0; j < st_objects; j++)
scanf("%d",&array[i][j]);

关于c 扫描二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601261/

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