0

我在数组中写了一个 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

4 回答 4

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
于 2013-07-30T13:15:54.203 回答
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);
于 2013-07-30T13:21:27.140 回答
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;
}
于 2013-07-30T13:46:42.097 回答
-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;
        }
    }
}

这应该适合你

于 2013-07-30T13:19:55.083 回答