JAVA 8: 计算平均值

huangapple go评论137阅读模式
英文:

JAVA 8 : Calculate the mean

问题

我有一个计算平均值的问题。

让我们假设,我们需要知道平均得分,所以我们将调查的得分相加然后取平均值。

所以,如果我们有:

调查 1:+1
调查 2:-1,-1,-1,+1
调查 3:+1

平均值将是 (+1 -1 -1 -1 +1 +1) / 6 = 0

首先要修改的事情是,获得所有调查的平均分数:

调查 1:1
调查 2:-0.75
调查 3:1

然后计算调查的平均值 (1 - 0.75 + 1) / 3 得到 0.41

我计算每个调查的平均值如下,以第二个调查为例:

	int survey2[] = {-1, -1, -1, 1};
    int sum =  0;
    for (int number : survey2) {
		sum += number;
	}
    float averageSurvey2 = (float) sum / survey2.length;
    System.out.println(averageSurvey2);

但是我得到的结果是 -0.5 而不是 -0.75,这是错误的。

英文:

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

答案1

得分: 3

问题是一个数学问题,而不是编程问题。

你认为调查2的平均值应该是-0.75,但实际上不应该是这样。它的平均值应该是-0.5。让我为你解释一下。

调查2的总和 = -1 + -1 + -1 + 1
调查2的总和 = ( -1 + -1 ) + ( -1 + 1 )
调查2的总和 = -2 + 0
调查2的总和 = -2

调查2的数量 = 1 + 1 + 1 + 1
调查2的数量 = 4

调查2的平均值 = (调查2的总和) / (调查2的数量) 
调查2的平均值 = ( -2 ) / ( 4 )
调查2的平均值 = -0.5

这是编程中的一个重要教训。如果你构建一个单元测试(即使你没有对这个程序进行单元测试,你实际上是在手动地进行单元测试),你的测试中可能会有错误(以及你的程序中可能会有错误)。

祝你好运,为你的程序能够正常运行感到高兴。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月27日 20:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64088325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定