• Post Reply Bookmark Topic Watch Topic
  • New Topic

For Loop  RSS feed

 
Carmenia Bona
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am really new in Java programming and I am doing some exercises in Java.
The program is supposed to display the sum and average. Like this:

The sum is 5050
The average is 50.5

But my code won't display the decimal.

Can somebody help me?

Here's my code:


public class sumandaverage {
public static void main(String[] args) {
int sum = 0;
double average = 00.0;
int lowerbound = 1;
int upperbound = 10;

for (int number = lowerbound; number <= upperbound; ++number) {
sum += number;
}

average = sum / upperbound;

System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}



Thanks so much!!!
 
Ramesh Kumar Muthukumar
Greenhorn
Posts: 8
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
average = sum / upperbound;


both the 'sum' and 'upperbound' are int values and the result also will be int and then it is converted into double.

that is why you get 50.0 instead of 50.5.

There are many ways to get the expected output. one of them is changing the upperbound and lowerbound datatype to double.

 
Carmenia Bona
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramesh Kumar Muthukumar wrote:
average = sum / upperbound;


both the 'sum' and 'upperbound' are int values and the result also will be int and then it is converted into double.

that is why you get 50.0 instead of 50.5.

There are many ways to get the expected output. one of them is changing the upperbound and lowerbound datatype to double.



Thanks you! It worked. May I know what are the other ways?
 
Ramesh Kumar Muthukumar
Greenhorn
Posts: 8
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
average = (double) sum / upperbound;

this also works.
 
Carmenia Bona
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramesh Kumar Muthukumar wrote:average = (double) sum / upperbound;

this also works.



thanks. i will try this next time. :)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!