+ 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); } }
6 Antworten
+ 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);
}
}
+ 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😊😊
+ 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.
+ 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.
+ 3
Also in the for loop, please use post-increment instead of pre-increment, see @Tashi N answer for clarity of difference.
+ 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