c - 如何在C中的二维数组中找到最高和最低数字及其位置
问题描述
我是新来的。我开始学习编程和C++。我必须做一个程序,向用户请求数字来填充一个数组,然后是一个函数来查找最高和最低值及其在数组中的位置。这就是我现在所拥有的,它可以找到最高的数字及其位置,但它不能找到最低的,找到的最低值是不正确的,或者它的位置:
int main() {
int array[SIZEF][SIZEC];
int zero = 0;
int highest[0][0]; //to find the highest, array from 0 value.
int lowest[0][0]; //to find the lowest, takes the highest value and then compare, if its lower than the current value of the array, it takes its value
highest[0][0] = zero;
fill_array(array, SIZEF, SIZEC);
highlow(array, SIZEF, SIZEC, highest, lowest);
getchar();
return 0;
}
void fill_array(int array[][SIZEC], int sizef, int sizec) {
//code to fill the array, no problem here.
}
void highlow(int array[][SIZEC], int sizef, int sizec, int highest[][0], int lowest[][0]) {
int positionX = 0;
int positionY = 0;
for (int i = 0; i < sizef; i++) {
for (int j = 0; j < sizec; j++) {
if (array[i][j] > highest[0][0]) {
//if the current value of the array is higher than highest value, highest value takes its value.
highest[0][0] = array[i][j];
positionX = i;
positionY = j;
lowest[0][0] == highest[0][0]; //now lowest value its the highest value
if (array[i][j] < lowest[i][j]) { //so, if current array value its lower than lowest value
//lowest value takes its value.
lowest[0][0] = array[i][j];
}
}
}
}
}
非常感谢。(对不起,我的英语,我也在学习)。
解决方案
int highest[0][0]; //to find the highest, array from 0 value. int lowest[0][0]; //to find the lowest, takes the highest value and then compare, if its lower than the current value of the array, it takes its value
这两个数组允许包含 0 个元素,维度为 0(注意 ISO C 禁止零大小数组)
所以在
highest[0][0]=zero;
你写出数组,就像你可以访问这两个数组之后的每一个地方
为什么不将它们调整为数组?我说因为lowest[i][j]
你程序的其他地方,即使这看起来很奇怪
如果我忘记了这两个向量的维度问题,在
lowest[0][0]==highest[0][0];
那句话什么也没做,可能是你想要的
lowest[0][0]=highest[0][0];
? 即使这看起来很奇怪
如果我忘记了这两个向量的维度问题,在
if(array[i][j] < lowest[i][j])
你永远不会写最低,除非[0][0]
是lowest[i][j]
未定义的,除非 i 和 j 为 0
您在main中调用fill_array
and时没有声明/定义,因为它们是在main之后定义的,编译器将使用您调用中的默认声明,这很危险,请将它们移到main之前或在main之前声明它们highlow
关于尺寸:
int a[10]
允许存储 10 个 int,索引为 0 .. 9
int highest[2][3]
允许存储 2*3 = 6 int,第一个索引是 0..1,第二个索引是 0..2
ETC
您的数组允许存储 0*0 = 0 个元素,您是否只需要访问highest[0][0]
您需要为其他数组定义它们int highest[1][1];
,但在这种情况下有什么兴趣?你只需要一个 int var,而不是一个数组
我鼓励您需要阅读有关 C 语言的书籍/教程
我还鼓励您在编译时请求高级别的警告/错误,例如,如果您使用gcc dogcc -pedantic -Wall ....
推荐阅读
- junit - junit 测试因异常而失败
- r - 在 R 中使用 for 循环创建不同的数据表
- client-side - 在 oEmbed API 中使用缩短的 SoundCloud 应用程序 url
- flutter - 使用带有 github 操作的 Flutter Web 时如何访问机密
- php - laravel中未定义的方法'json'
- python - 从数据库中获取ID对应的一行,并在提示时替换文本框中的数据
- c# - 在将输入列表与作为对象属性的列表进行比较后返回 obj 结果的 Linq 查询
- python - 无法从 Flask 读取函数中的值
- google-sheets - 如果单元格值在另一列中,如何有条件地格式化列
- wordpress - 如何将来自 Theme > Customize 的数据添加到 WPGraphQL Schema?