【发布时间】:2015-01-25 11:42:46
【问题描述】:
我正在尝试用 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,并了解一点standard C++ algorithms。 -
从技术上讲,不需要向量,因为所有值都可以即时计算。
-
@Jasper 好点。我不确定这是否比
std::vector更容易,但它肯定比任何其他解决方案都更容易(这或多或少需要重新实现std::vector)。