+ 3

I want to get the average in double and the output must be 50.5. How do I get it and what's wrong with my code?

public class Program { public static void main(String[] args) { int sum=0; double average =0; int lowercase=1, uppercase=100; for(int number = lowercase; number <= uppercase; ++number){ sum+=number; } System.out.println(sum); for(double number = lowercase; number <= uppercase; ++number){ average +=number; } System.out.println(average); } }

8th Sep 2017, 3:04 PM
jomar ibarra
jomar ibarra - avatar
6 Respuestas
+ 10
Something like this... public class Program { public static void main(String[] args) { int sum=0, count=0; double average=0; for(int i=1; i<=100; i++){ count++; sum+=i; } average=sum/(double)count; System.out.println("sum: "+sum); System.out.println("count: "+count); System.out.println("avg: "+average); } }
8th Sep 2017, 3:32 PM
Tashi N
Tashi N - avatar
+ 5
Thank you very much sir.. sadly I'm not skipping my math lessons, its just that I'm not that good in math either, but thank you very much I really appreciate it😊😊
8th Sep 2017, 3:31 PM
jomar ibarra
jomar ibarra - avatar
+ 5
@lpang Why though? There is no difference. Both compile the same bytecode and are pretty much the same as far as readability/maintainability goes. Doesn't really matter.
8th Sep 2017, 6:55 PM
Rrestoring faith
Rrestoring faith - avatar
+ 5
@Rrestoring Faith, I was referring to these lines (on the question): for(int number = lowercase; number <= uppercase; ++number) ... and these... for(double number = lowercase; number <= uppercase; ++number) ... I guess I'm much more accustomed to see post-increment in for loops rather than pre-increment. I'm sure you knew there are difference between the two, but yes, like you said, they are of the same, in this case, it's just a matter of preference.
9th Sep 2017, 2:38 AM
Ipang
+ 3
Also in the for loop, please use post-increment instead of pre-increment, see @Tashi N answer for clarity of difference.
8th Sep 2017, 5:03 PM
Ipang
+ 3
thank you for your answers people I don't know what to say but all thank you, thank you very much it help me alot
8th Sep 2017, 11:23 PM
jomar ibarra
jomar ibarra - avatar