平均,最大和总和在未知大小的数组C ++中
avg, biggest and sum in unknown sized array c++
我试图用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>
不是很便携,而且在支持它的系统上已弃用。
如果您不能使用 std::vector
,您可能需要了解动态内存分配。
int *a = new int[size];
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 我需要将数组传递给函数以平均不同的测试分数
- 如何将移动平均线写入数组列表类?
- 如何在结构数组中显示学生姓名以及高于平均 GPA 的 ID
- 传递数组和计算平均C++的问题
- 数组的平均分数
- 平均,最大和总和在未知大小的数组C ++中
- 获取 2D 数组中数字的平均、最小值和最大值
- 我有一个C++2d数组,我必须调用函数.它只对每5个位置进行平均,例如[0][0]+[5][0]这看起来是否正确,或者有