Task

我想从输入中获取一个整二维数组的最大元素.

My code

#include<stdio.h>
int main(void)
{
    /*********Begin*********/
    printf("Input m, n:");
    int m,n;
    int max=0; 
    scanf("%d,%d",&m,&n);
    int s[10][10];
    printf("Input %d*%d array:\n",m,n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            scanf("%d",&s[i][j]);
        }
    }
    int row,col;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(s[i][j]>max){
                max=s[i][j];
                row=i;
                col=j;
            }

        }
    }
    printf("max=%d, row=%d, col=%d",max,row,col);




    return 0;
}

Tested case

// input
2,1

1

2
// output
Input m, n:Input 2*1 array:
max=2, row=1, col=2

预期结果:

Input m, n:Input 2*1 array:
max=2, row=2, col=1

为什么输出行和列相反?或者输出的行和列实际上不正确.

推荐答案

上面的所有 comments 都有效,并反映在下面的代码中.我给你的解决方案不是给你答案,而是向你展示一些喜欢的编码实践,正如你说你是一名学生,建议你尽早学习编码风格.特别注意我大量使用空白,这使得代码更容易阅读.

(我还预先定义了您的矩阵,这样我就不必手动输入所有数字;您可以撤销这一点.)

#include <limits.h>
#include <stdio.h>

int main(void)
{
#define NBR_ROWS 5
#define NBR_COLUMNS 5

    const int matrix[NBR_ROWS][NBR_COLUMNS] = {
        { 1, 2, 3, 4, 5},
        { 4, 5, 6, 100, 2 },
        { 3, 2, 1, 5, 6 },
        { 1, 2, 3, 5, 4 },
        { 3, 5, 6, 4, 8 }
    };
    int max = INT_MIN;
    int row;
    int col;

    for (int i = 0; i < NBR_ROWS; i++){
        for (int j = 0; j < NBR_COLUMNS; j++) {
            if (matrix[i][j] > max) {
                max = matrix[i][j];
                row = i;
                col = j;
            }
        }
    }
    printf("max=%d, row=%d, col=%d", max, row, col);

    return 0;
}

C++相关问答推荐

如何在C中的空指针函数中传递浮点值

初始化char数组-用于初始化数组的字符串是否除了存储数组的位置之外单独存储在内存中

CC crate 示例不会与C函数链接

C中空终止符后面的数字?

为什么下面的C代码会进入无限循环?

Mise()在虚拟内存中做什么?

两个连续的语句是否按顺序排列?

GLIBC:如何告诉可执行文件链接到特定版本的GLIBC

C lang:当我try 将3个或更多元素写入数组时,出现总线错误

C中的指针增量和减量(*--*++p)

Setenv在c编程中的用法?

==284==错误:AddressSaniizer:堆栈缓冲区下溢

如何只获取字符串的第一个单词,然后将其与c中的另一个单词进行比较?

使用ld将目标文件链接到C标准库

int * 指向int的哪个字节?

在吉陀罗中,_2_1_和CONCAT11是什么意思?

与外部SPI闪存通信时是否应禁用中断?

%g浮点表示的最大字符串长度是多少?

为什么程序在打印每个数字之前要等待所有输入?

与 C 相比,C++ 中无副作用的无限循环的好处是 UB?