我正在编写一个程序,该程序声明一个名为mynumbers的二维数组。该程序应静态初始化数组mynumbers的8个元素并显示 1.最小元素 2.最大元素
这是我尝试过的。
#include <stdio.h>
int main(){
int mynumbers[2][4]={{17,27,13,32},{18,52,19,62}};
int largenum = mynumbers[1][2];
int leastnum = mynumbers[0][1];
if(mynumbers[0][0]>largenum)
{
largenum = mynumbers[0][0];
}
else largenum =largenum;
if(mynumbers[0][1]>largenum)
{
largenum = mynumbers[0][1];
}
else largenum =largenum;
if(mynumbers[0][2]>largenum)
{
largenum = mynumbers[0][2];
}
else largenum =largenum;
if(mynumbers[0][3]>largenum)
{
largenum = mynumbers[0][3];
}
else largenum =largenum;
if(mynumbers[1][0]>largenum)
{
largenum = mynumbers[1][0];
}
else largenum =largenum;
if(mynumbers[1][1]>largenum)
{
largenum = mynumbers[1][1];
}
else largenum =largenum;
if(mynumbers[1][2]>largenum)
{
largenum = mynumbers[1][2];
}
else largenum =largenum;
if(mynumbers[1][3]>largenum)
{
largenum = mynumbers[1][3];
}
else largenum =largenum;
{
printf("the largest number is :%d/n",largenum);
}
//else leastnum =leastnum;
if(mynumbers[0][0]<leastnum)
{
leastnum = mynumbers[0][0];
}
else leastnum =leastnum;
if(mynumbers[0][1]<leastnum)
{
leastnum = mynumbers[0][1];
}
else leastnum =leastnum;
if(mynumbers[0][2]<leastnum)
{
leastnum = mynumbers[0][2];
}
else leastnum =leastnum;
if(mynumbers[0][3]<leastnum)
{
leastnum = mynumbers[0][3];
}
else leastnum =leastnum;
if(mynumbers[1][0]<leastnum)
{
leastnum = mynumbers[1][0];
}
else leastnum =leastnum;
if(mynumbers[1][1]<leastnum)
{
leastnum = mynumbers[1][1];
}
else leastnum =leastnum;
if(mynumbers[1][2]<leastnum)
{
leastnum = mynumbers[1][2];
}
else leastnum =leastnum;
if(mynumbers[1][3]<leastnum)
{
leastnum = leastnum[1][3];
}
else leastnum =leastnum;
{
printf("the smallest number is :%d/n",leastnum);
}
}
我遇到以下错误
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\Admin\Documents\Untitled1.c||In function 'main':|
C:\Users\Admin\Documents\Untitled1.c|87|error: subscripted value is neither array nor pointer nor vector|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
答案 0 :(得分:3)
编译时会出现以下错误:error: subscripted value is neither array nor pointer nor vector leastnum = leastnum[1][3];
,因为您将leastnum
声明并初始化为int
而不是int[][]
,这很清楚。然后,您可能要写leastnum = mynumbers[1][3]
。
此外,您还缺少使用循环的好机会:您正在手工比较二维数组的每个值。这是您可能如何凝结所有if else
条件的方法:
#include <stdio.h>
int main(void){
int mynumbers[2][4]={
{17,27,13,32},
{18,52,19,62}
};
int min = **mynumbers; // <=> int min = mynumbers[0][0]
int max = **mynumbers;
int row = sizeof(mynumbers) / sizeof(mynumbers[0]); // = (8*4) / (4*4) = 2
int column = sizeof(mynumbers[0]) / sizeof(int); // = (4*4) / 4 = 4
for(int i=0; i<row; i++){
for(int j=0; j<column; j++){
if(mynumbers[i][j] < min) min = mynumbers[i][j];
if(mynumbers[i][j] > max) max = mynumbers[i][j];
}
}
printf("Min: %d\nMax: %d\n", min, max);
return 0;
}