【问题标题】:How to find the average of the difference between the largest and smallest elements in all rows of an 2D array using C如何使用C找到二维数组所有行中最大和最小元素之间差异的平均值
【发布时间】:2022-01-25 12:38:15
【问题描述】:

有人给了我一个用 C 语言解决的问题,但我很困惑。

编写一个C程序,可以显示四个城市最近五天的温度,并显示所有城市的最高和最低温度之差的平均值

示例输入

20 27 28 22

12 22 12 20

22 24 25 33

33 30 30 29

样本输出

7.75

我已经厌倦了从二维数组的每一行中找出最大和最小元素之间的差异。但是现在我面临着如何存储每行的差异并找到平均值?这是我的一段代码-

#include<stdio.h>

int main()
{
    int array1[10][10];
    int num, row, column;

    printf("How many rows and columns are needed: ");
    scanf("%d %d", &row, &column);

    printf("\nHow many cities temperature you want to enter: ");
    scanf("%d", &num);

    printf("\nEnter %d cities temperature: ", num);

    for(int i=0; i<row; i++)
    {
        for(int j=0; j<column; j++)
        {
            scanf("%d", &array1[i][j]);
        }
        printf("\n");
    }

    for(int i=0; i<row; i++)
    {
        int largeA = array1[i][0];
        int smallA = array1[i][0];

        for(int j=0; j<column; j++)
        {
            if(array1[i][j] > largeA)
            {
                largeA = array1[i][j];
            }
            if(array1[i][j] < smallA)
            {
                smallA = array1[i][j];
            }
        }
        unsigned diff = 0u +  largeA - smallA;
        printf("%d\n", diff);
    }

    return 0;
}

【问题讨论】:

  • 您不需要每天的最高和最低温度或其差异的任何数组。您只需要存储这些差异的一个运行总数。每天,找出最低和最高,并将它们的差值加到总数中。最后将总数除以天数。
  • 您的示例包含四行,每行四个数字,而描述说输入应包含 4×5 值。

标签: c multidimensional-array


【解决方案1】:

您可以创建另一个一维数组来保存每个城市的温差。

平均温差将是这个数组的平均值。

【讨论】:

  • 我还是一头雾水。你能启发我吗?
猜你喜欢
  • 2019-08-28
  • 2017-09-28
  • 2022-01-25
  • 1970-01-01
  • 2021-11-13
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多