I wanted to know how I could add all of the elements of a float array together and make the sum float average;. Would I have to use a for loop or is there another way to add element 0 with 1 with 2 with 3, etc.?
-
Is this a homework assignment?N_A– N_A2011-10-05 14:40:43 +00:00Commented Oct 5, 2011 at 14:40
-
2Adding a bunch of floats is tricky, does the result have to be "as precise as possible", just "a bit precise" or can it be "naively sum them" (the difference with the actual sum can be quite big in that case)user555045– user5550452011-10-05 15:04:56 +00:00Commented Oct 5, 2011 at 15:04
-
@harold: from another question of Chris, it seems that those are grades, so the magnitude of the elements should be about the same. In this case, I think precision is not too much of an issue.Matthieu M.– Matthieu M.2011-10-05 16:47:50 +00:00Commented Oct 5, 2011 at 16:47
Add a comment
|
2 Answers
You may use a for loop, or you can use std::accumulate.
#include <iostream>
#include <numeric>
int main()
{
float arr[17] = { 1, 2, 3, };
//Sum the array
const float sum = std::accumulate(arr, arr+17, 0.0 );
std::cout << "Sum: " << sum << "\n";
std::cout << "Average: " << sum/17 << "\n";
}
2 Comments
Mooing Duck
while a good answer, that comment in the middle is a bit misleading :D
Robᵩ
Thanks, @MooingDuck. As you might imagine, I didn't write my answer from scratch. I cribbed it from a "how to sum
std::vector" example.