0

Age average

Why I can’t get correct result , 28.4? public class Program { public static void main(String[] args) { int grace = 10; int edward = 21; int rose = 15; int mom = 46; int dad = 50; float average = (grace+edward+rose+mom+dad)/5; System.out.println(average); } }

25th Oct 2019, 12:11 AM
Mali
4 Respostas
+ 1
You defined the numbers as integers, so when they are divided, they are divided as integers, rounding the decimal to whole number. If you want to keep the decimal, try: //my code is in C#, adapt it to Java using System; public class Program { public static void Main(String[] args) { float grace = 10; float edward = 21; float rose = 15; float mom = 46; float dad = 50; float average = (grace+edward+rose+mom+dad)/5; Console.WriteLine(average); } }
25th Oct 2019, 1:00 AM
Rodrigo Oliveira
Rodrigo Oliveira - avatar
+ 2
What does this output?
25th Oct 2019, 12:16 AM
Álvaro Rodríguez García
Álvaro Rodríguez García - avatar
+ 2
Why is that not true? To show avg age of array int ages[] = {19, 24, 36, 45, 56, 52, 21, 27, 24, 34, 29, 60, 40, 42, 45, 47, 22, 30, 34, 20, 18, 26, 51, 43, 47, 39, 22, 34, 56, 52, 21, 27, 24, 37, 19, 24, 36, 45, 44, 49, 23, 25, 19, 40, 29, 60, 40, 42, 45, 47, 61, 30, 19, 43, 47, 39, 41, 46, 29, 24, 21, 25, 28}; int size = 63; int *p = ages; int avg; for(int i=0;i<size;i++) { cout << *p << endl; avg += *p; p++; } cout<<avg/size;
28th Sep 2023, 8:21 PM
Vladyslav Sabadakh
Vladyslav Sabadakh - avatar
0
24.0
25th Oct 2019, 12:21 AM
Mali