Reputation: 271
I have a problem to calculate the average
let's admit, we need to know the average vote, so we add the votes of the surveys and we do the average.
So that if we have
Survey 1 : +1
Survey 2 : -1, -1, -1, +1
Survey 2 : +1
The average will be (+1 -1 -1 -1 +1 +1) / 6 = 0
So first thing to modify, have the average mark of all the surveys
Survey 1 : 1
Suveey 2 : -0,75
Survey 3 : 1
And then calculate the average of the surveys (1 - 0,75 +1) / 3 to have 0.41
I calculate the average of each survey as follows, take the case of the 2nd survey :
int survey2[] = {-1, -1, -1, 1};
int somme = 0;
for (int nombre : survey2) {
somme += nombre;
}
float moyenneSurvey2 = (float) somme /survey2.length;
System.out.println(moyenneSurvey2);
but I have a result of -0.5 instead of -0.75 which is wrong
Upvotes: 2
Views: 144
Reputation: 70909
The problem you have is a math problem, not a programming problem.
You think that survey 2 should have a mean of -0.75, but it should not. It should have a mean of -0.5. Let me show you why.
sum of survey 2 = -1 + -1 + -1 + 1
sum of survey 2 = ( -1 + -1 ) + ( -1 + 1 )
sum of survey 2 = -2 + 0
sum of survey 2 = -2
count of survey 2 = 1 + 1 + 1 + 1
count of survey 2 = 4
mean of survey 2 = (sum of survey 2) / (count of survey 2)
mean of survey 2 = ( -2 ) / ( 4 )
mean of survey 2 = -0.5
this is an important lesson in programming. If you construct a unit test (which even if you are not unit testing this program, you basically built a unit test you are following manually), you can have errors in your test (as well as errors in your program).
Good luck, and be happy your program works.
Upvotes: 3