0

I've been running this code but I have not been able to get an accumulation of doubled figures.

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main(){
    vector<double> student_marks;
    size_t num_students;

    cout<<"Number of students:";
    cin>>num_students;

    student_marks.resize(num_students);

    for(size_t i=0;i<student_marks.size();i++){
        cout<<"Enter mark of student #"<<i+1<<":";
        cin>>student_marks[i];
    }

    double sum_mark = accumulate(student_marks.begin(), student_marks.end(), 0);

    cout<<"Total mark:"<<sum_mark<<endl
    <<"Average mark:"<<sum_mark/student_marks.size()<<endl;

    return 0;
}

Here's an example of the I/O:

Number of students:3
Enter mark of student #1:1.8
Enter mark of student #2:2.3
Enter mark of student #3:3.4
Total mark:6
Average mark:2

The Total mark here should be 7.5, but the compiler is completely ignoring the fractional portion, and is only calculating with the integer portion, as if I entered the figures as an integer. I thought accumulate supports basically any type of figure, however it seems that I'm not able to tell it to accumulate the figures as double. I ran a cout on a single element, and it was outputted with the fractional portion so at least I know that something is wrong with the accumulator. I tried casting several parts of the operands to double, but it didn't work.

coffeeFlow
  • 179
  • 1
  • 6

2 Answers2

2

accumulate deduces its accumulator type from the initial value argument. Try:

double sum_mark = accumulate(student_marks.begin(), student_marks.end(), 0.0);
                                                                         ^^^
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1
accumulate(student_marks.begin(), student_marks.end(), 0);

Because you passed in the integer 0, the template was instantiated with the type int, causing all the enumerated doubles to be truncated to integers. You need to pass in a double for your initial value. As a side note, turn on all compiler warnings. Your compiler should warn you about this truncation.

accumulate(student_marks.begin(), student_marks.end(), 0.0);
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98