显示矢量值

时间:2017-04-02 07:35:59

标签: c++ vector

我正在尝试将我的向量的所有值添加到一起并获得平均值,但我收到错误消息。

这是我对作业的指示,所以你们可以更好地理解

1)从用户

接受15个等级到向量中

额外的高级挑战和要求:

当且仅当它大于0.00时才接受该号码。当且仅当它是有效类型double时接受该数字。那就是每次在将值填充到向量之前以这种方式进行验证?

2)在数字被接受到矢量后,计算并显示15个输入数字的平均值。

3)使用冒泡排序(或矢量原生的其他方法/算法),将数组中的15个数字从最大到最小排序。提示:向量是否有内置的排序方法?我们如何让向量按此处的要求降序排序,而不是标准的放宽?

4)显示已排序的gradesVector

以下是错误消息:

main.cpp:43:10: error: use of undeclared identifier 'sum'
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     ^
main.cpp:43:42: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                      ~~~~~~~~~~~~~~~^~~~~~
main.cpp:43:67: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                                               ~~~~~~~~~~~~~~~^~~~
main.cpp:44:10: error: use of undeclared identifier 'average'
     average = sum/15;
     ^
main.cpp:44:20: error: use of undeclared identifier 'sum'
     average = sum/15;
               ^
main.cpp:46:18: error: use of undeclared identifier 'average'
     cout << average;

以下是代码:

vector<double> gradesVector;
gradesVector.reserve(15);


for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;       
do
  {

    if(c!=0)   

      cout << "Invalid Rage. Please Enter Range 0-100:\n";         
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;   
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     average = sum/15;

     cout << average;

        }

1 个答案:

答案 0 :(得分:-1)

这是答案

我忘了使用#include <numeric>

代码现在读取

vector<double> gradesVector(15);
double sum;
double average;

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;       
do
  {

    if(c!=0)   

      cout << "Invalid Rage. Please Enter Range 0-100:\n";         
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;   
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

这行代码使用#include <numeric>我还更改了gradesVector[i].begin()gradesVector[i].end()     到gradesVector.begin()gradesVector.end()

     sum = accumulate(gradesVector.begin(), gradesVector.end(), 0); 
     average = sum/15;



        }
cout << average;