Carmenia Bona

Greenhorn

Posts: 7

posted 4 years ago

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!!!

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!!!

posted 4 years ago

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.

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

posted 4 years ago

Thanks you! It worked. May I know what are the other ways?

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?

It is sorta covered in the JavaRanch Style Guide. |