首页 > 解决方案 > C++ 数组和元素

问题描述

我的程序专注于这个实验室的数组元素,但我不确定如何将我的平均值设置为请求的特定数字。任何指导都会对这篇文章有所帮助

#include "pch.h"
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    int arr[10], n, i, max, min, avg;
    cout << "Enter the size of the array: ";
    cin >> n;
    cout << "Enter the elements of the array: ";
    for (i = 0; i < n; i++)
        cin >> arr[i];
    max = arr[0];
    for (i = 0; i < n; i++)
    {
        if (max < arr[i])
            max = arr[i];
    }
    min = arr[0];
    for (i = 0; i < n; i++)
    {
        if (min > arr[i])
            min = arr[i];
    }
    avg = arr[0];
    for (i = 0; i < n; i++)
    {
        if (avg > arr[i])
            avg = arr[i];
    }
    cout << "Largest element: " << max;
    cout << "Smallest element: " << min;
    cout << "Average element: " << avg;
}

标签: c++

解决方案


我建议在你的 for 循环中使用 += 运算符,然后除以 n。

float sum = 0;
float avg = 0;
for(i = 0; i < n; i++)
{
    sum += arr[i];
}
avg = sum / n;

另外,我建议您使用浮点数或双精度数,而不是使用整数作为平均值,否则您将进行整数除法,这将截断小数。即 5 / 2 = 2


推荐阅读