Scanner scan = new Scanner(System.in);
int count = 0;
int sum = 0;
while (true) {
int num = scan.nextInt();
if (num == -1)
break;
count++;
sum = sum + num;
}
double med = sum / count;
System.out.println(med);
This is what I wrote, but the program doesn't calculate the solution correctly. when I use the numbers 1,2,2,4,5,-1 it's solution is 2.0, not 2.8. same for 4,3,2,1,-1.
I can't figure out why, since the break happens before the calculation, the -1 shouldn't be counted neither for sum, nor for count. What am I not seeing?
Thanks for the help in advance.
not calculating correctly - what am I doing wrong?
Gelöst
Kommentare (2)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Thomas
11 September 2022, 14:03Lösung
sum and count both are ints. If you divide one by the other, then it is an int division. Means that all decimal places are cut off. E.g. 3 / 2 is not 1.5 but the .5 is cut off and the result is 1. If you need the decimal places, then you need a double division. At least on of the numbers needs to be a double then the other(s) automatically get casted to doubles, too. Like 1.0 * sum / count or (double) sum / count
+2
G_Nod
14 September 2022, 15:46
I see, thank you
0