平均,最大和总和在未知大小的数组C ++中

avg, biggest and sum in unknown sized array c++

本文关键字:数组 平均 未知      更新时间:2023-10-16

我试图用c ++编写一个控制台应用程序,该应用程序将允许用户输入一系列数字,程序应该得到所有数字的总和,平均数字,最大和第二大数字。例如:

输入几个数字:10 12 -5 20 -2 15 0

总和 = 50

平均值 = 8.3

最大数字 = 20

第二大 = 15

#include<iostream>
#include<conio.h>
using namespace std; 
int main( )
{

int a[5];
cout << "We are going to find the max value"<< endl;
int x;
    for (x=0; x<5; x++)
    {
        cout<<"insert values"<<x+1<<endl;
            cin>>a[x];
    }
    int max;
    int min;
    max = a[0];
    min = a[0];
    int e=0;
        while (e<5)
        {
            if (a[e]>max)
            {
                max = a[e];
            }
            e++;
        }
        cout<<"Max value in the array is.."<<max<<endl;
    getch();
    return 0;
 }

这是我迄今为止的进步。虽然,我有一些担忧。如何让用户像示例中那样输入数字并将它们存储在大小未知的数组中?

我将尝试找出一种方法来计算平均值,总和和第二大,同时等待此答案:)

谢谢!

要输入未知数量的元素,请使用 std::vector ,输入直到用户告诉您停止,通常通过输入文件结尾:

std::vector<int> values;
int i;
while ( std::cin >> i ) {
    values.push_back( i ) ;
}

如果您正在寻找其他类型的信号,您将可能必须逐行阅读,检查该行是否包含您的结束标准,然后使用 std::istringstream 解析整数。

其余的:它可能与练习的目标不符,但标准库有几个功能,可以做一些事情明显更简单:例如std::max_elementstd::accumulate . 而且<conio.h>不是很便携,而且在支持它的系统上已弃用。

如果您不能使用 std::vector ,您可能需要了解动态内存分配。

int *a = new int[size];