programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# For Loop

Greenhorn
Posts: 7
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!!!

Greenhorn
Posts: 8

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

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
average = (double) sum / upperbound;

this also works.

Carmenia Bona
Greenhorn
Posts: 7

Ramesh Kumar Muthukumar wrote:average = (double) sum / upperbound;

this also works.

thanks. i will try this next time. :)

 All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad: Rocket Oven Kickstarter - from the trailboss https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss