gpt4 book ai didi

c++ - 未知大小数组c++中的平均,最大和总和

转载 作者:行者123 更新时间:2023-11-30 05:48:32 26 4
gpt4 key购买 nike

我试图用 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_element ,例如,或 std::accumulate .和 <conio.h>不是很便携,并且是在支持它的系统上已弃用。

关于c++ - 未知大小数组c++中的平均,最大和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com