C - 未知数字中的最大数字

标签 c matrix max

我又来了,请求你的帮助。

我将在下面提出问题,这是我的代码:

#include <stdio.h>

int main ()
{
    int matrix[10][10];
    int nrows, ncols, i, j, tmp, rsum, smax;

    printf("Enter number of rows: "); //user enters number of rows
    scanf("%d", &nrows);
    if(nrows < 2){
        printf("\n Out of range, please try again");
        exit(5);
    }

    printf("Enter number of columns: "); //user enters number of columns
    scanf("%d", &ncols);
    if(ncols < 2){
        printf("\n Out of range, please try again");
        exit(5);
    }

    printf("Enter matrix elements: "); //user enters all the elements for Matrix
    //Run over every element + ONLY POSITIVE LOOP
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            tmp=0;
            scanf("%d",&tmp);
            while(tmp<0){
                printf("Only Positive Numbers!!!\n");
                scanf("%d",&tmp);
            }
            matrix[i][j]=tmp;
        }
    }

    //Print finished matrix
    printf("This is your matrix: \n");
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            printf("%d \t",matrix[i][j]);
        }
        printf("\n");
    }

    //Print sum of each row
    for(i=0; i<nrows; i++){
        rsum = 0;
        for(j=0; j<ncols; j++){
            rsum += matrix[i][j];
        }
        printf("\nSum of elements of Row %d = %d\n", i+1, rsum);
    }

    //print row with highest sum

    return 0;
}

所以,我有矩阵并且有一些任务要做,限制用户只能输入正数,每行的总和等。 现在我需要从行的总和中找到最大的数字,我不知道我会有多少数字,我需要一些可以处理任何数量的数字的东西。

这是代码输出:

Enter Number Of Rows: 3
Enter Number of Columns: 3
Enter Elements: 1 2 3 4 5 6 7 8 9

This Is Your Matrix:
1   2   3
4   5   6
7   8   9

Sum Of Elements Of Row 1 = 6
Sum Of Elements Of Row 2 = 15
Sum Of Elements Of Row 3 = 24

我想检查所有行的总和并打印出最大的一个,对于上面的示例,应该将类似这样的内容添加到此输出中:

Row With Largest Sum [Row Number] = [Row Sum]

等待您的帮助。

最佳答案

获得行数和列数后定义矩阵,如下所示:

unsigned rows = 0;
unsigned columns = 0;

// Rows
printf("Number of rows: ");
scanf("%u", &rows);

// Columns
printf("Number of columns: ");
scanf("%u", &columns);

// Matrix
int matrix[rows][columns];

关于C - 未知数字中的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47956135/

相关文章:

c - sscanf 写入字符数组

r - 如何根据最终列值对矩阵中的列进行排序?

matlab - 获取矩阵的偶数/奇数索引 - MATLAB

php - foreach 最大数组值?

c - 如何使 scanf() 的否定扫描集在循环中工作?

c - 如何在一行中读取C中的多个scanf输入?说 200 默克 58.9?

java - 如何检查矩阵是否对称?

java - 最大和最小数量

php - Mysql 2跨 TableView 不将1=1关系转化为一个 View

c - Windows WFP驱动程序: Getting BSOD when processing packets in ClassifyFn callback