vector - C++ : why is my average returning as an int and not a double? -


this question has answer here:

i declared average double @ beginning of int main(). code compiles , runs fine, except when calculates average returns int. goal of assignment create , fill vector, calculate average , find median. stuck on part. ideas??

thanks , appreciate help.

#include <iostream> #include <vector> #include <cmath> #include <numeric> using namespace std;  int main() {     int n;     double average=0;      cout<<"vector length?: "<<endl;     cin>>n;     vector<int> data;     srand(time(null));      (int i=0; i<n; i++)     {         data.push_back(rand()%10+1);     }     (int i=0; i<data.size(); i++)     {         cout<<"vector: "<<i<<" "<< data[i]<<endl;     }      average = accumulate(data.begin(), data.end(), 0)/data.size();      cout<<"average: "<<average<<endl;      system ("pause");      return 0;      } 

the type of initial value parameter std::accumulate being deduced int. result of accumulation int , perform integer division.

change line

average = accumulate(data.begin(), data.end(), 0.0)/data.size(); //                                             ^^^ 

now type returned accumulate double.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -