找到vector c ++的输入平均值

alf*_*j12 4 c++ average vector

我正在尝试编写一个程序,用户输入尽可能多的数字,然后程序返回数字的平均值.到目前为止,程序只输出输入的最后一个数字.

#include <vector>
#include <iostream>
#include <numeric>


using namespace std;

int main()
{  
    vector<float> v;
    int input;

    cout << " Please enter numbers you want to find the mean of:" <<endl;
    while (cin >> input);
    v.push_back(input);

float average = accumulate( v.begin(), v.end(), 0.0/ v.size());
cout << "The average is" << average << endl;

return 0;  

}
Run Code Online (Sandbox Code Playgroud)

P0W*_*P0W 29

首先摆脱分号后 while

while (cin >> input);
                    ~~
Run Code Online (Sandbox Code Playgroud)

其次你数学错了

第三个参数std::accumulate是sum的初始

相反:

float average = accumulate( v.begin(), v.end(), 0.0)/v.size(); 
Run Code Online (Sandbox Code Playgroud)

此外,容器数据类型的元素与容器类型匹配,即float

使用 float input ;

  • 然后有人会尝试找到空范围的平均值......繁荣! (2认同)

swa*_*ang 6

您的代码中存在相当多的错误,您是否实际调试过它?这是一个工作版本:

#include <vector>                                                               
#include <iostream>                                                             
#include <numeric>                                                              


using namespace std;                                                            

int main()                                                                      
{                                                                               
    vector<float> v;                                                            
    float input;                                                                

    cout << " Please enter numbers you want to find the mean of:" <<endl;       
    while (cin >> input)                                                        
        v.push_back(input);                                                     

    float average = accumulate( v.begin(), v.end(), 0.0)/v.size();              
    cout << "The average is" << average << endl;                                

    return 0;                                                                   

}    
Run Code Online (Sandbox Code Playgroud)