C阵列 - 最大的数字和它的位置

时间:2013-07-30 13:10:26

标签: c arrays numbers location

我在数组中写了5x6随机数的代码,如何在其中找到最大数字然后打印它的位置(x,y)?

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main () {
 int array[5][6];
 srand(time(NULL));
 int x, y;
 for(x = 0; x < 5; x++) {
    for(y = 0; y < 6; y++) {
        array[x][y] = rand() % 31 + 10;
        printf("%d \t", array[x][y]);
   }
   printf("\n");
  }
 return 0;
}

4 个答案:

答案 0 :(得分:5)

int maxX = -1, maxY = -1;
int maxValue = 0
for(int x = 0; x < 5; x++) {
    for(int y = 0; y < 6; y++) {
        if(maxValue <= array[x][y]) {
            maxValue = array[x][y];
            maxX = x;
            maxY = y;
        }
    }
}
// print maxX and maxY and maxValue

答案 1 :(得分:0)

好吧,我注意到了这一点:

array[x][y] = rand() % 31 + 10;//So the values are between 10 and 40;

所以:

 int maxX = -1, maxY = -1;
int maxValue = 0
for(int x = 0; x < 5; x++) {
    for(int y = 0; y < 6; y++) {
        if(maxValue <= array[x][y]) {
            maxValue = array[x][y];
            maxX = x;
            maxY = y;
            if (maxValue == 40)//I add this in fact :) 
                 break;
        }
    }
}
 printf("the max value's locate %d,%d\n",maxX,maxY);

答案 2 :(得分:0)

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <limits.h>

int main(void){
    int array[5][6];
    srand(time(NULL));
    int x, y;
    int max = INT_MIN, *maxp=&array[0][0];
    for(x = 0; x < 5; x++) {
        for(y = 0; y < 6; y++) {
            if(max <(array[x][y] = rand() % 31 + 10)){
                max = *(maxp = &array[x][y]);
            }
            printf("%d \t", array[x][y]);
        }
        printf("\n");
    }
    printf("max=%d\n", max);
    ptrdiff_t pos = maxp - &array[0][0];
    size_t column_size = sizeof(array[0])/sizeof(array[0][0]);
    x = pos / column_size;
    y = pos % column_size;
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

答案 3 :(得分:-2)

int xMax, yMax, max;
xMax = yMax = 0;
max = array[0][0];

for(x=0;x<5;x++){
    for(y=0;y<6;y++){
        if(array[x][y] > max) {
                    max = array[x][y];
            xMax = x;
            yMax = y;
        }
    }
}

这应该对你有用