0

So i am having a difficult time trying to figure out how to get the values to come out properly. All of the math is correct, but it only stating whole numbers. For example, when i input the numbers 87, 42, and 94, the average should come out 74.3 repeating. Yet it only comes out 74.0 for me. Same goes with the average for lowest score.

Scanner keyboard = new Scanner(System.in);

int a;
int b;
int c;
double grade;
double avg;
double avg2 = 0;

System.out.print("Enter score number 1: ");
a = keyboard.nextInt();
System.out.print("Enter score number 2: ");
b = keyboard.nextInt();
System.out.print("Enter score number 3: ");
c = keyboard.nextInt();

avg = ((a + b + c) / 3);


System.out.println("The average is: " + avg);

if (a < b && a < c)
{
    System.out.println("The lowest score was: " + a);
    System.out.println("The average without the lowest score is: " + ((b + c) / 2));
    avg2 = ((b + c) / 2);
}


if (b < a && b < c)
{
    System.out.println("The lowest score was: " + b);
    System.out.println("The average without the lowest score is: " + ((a + c) / 2));
    avg2 = ((a + c) / 2);
}


if (c < a && c < b)
{
    System.out.println("The lowest score was: " + c);
    System.out.println("The average without the lowest score is: " + ((a + b) /2));
    avg2 = ((a + b) / 2);
}
Karthik T
  • 31,456
  • 5
  • 68
  • 87
user2045235
  • 1
  • 1
  • 3

4 Answers4

2

You must cast the sum in the numerator of your avg expression to a double or use a double in the denominator:

avg = ((double)(a + b + c) / 3);

or

avg = ((a + b + c) / 3.0);

cbush06
  • 46
  • 2
0

When you use all ints on the right hand side, the answer is calculated as an int before it is assigned to the double. This is why you are getting a rounded answer.

To fix, one option is to add decimal places to all your denominators like so

avg = ((a + b + c) / 3.0d);

This will force the operation to happen in double

Karthik T
  • 31,456
  • 5
  • 68
  • 87
0

A division between two ints will return an int. To cause the division that returns double, one of the operands must be a double, like so:

avg = ((a + b + c) / 3.0);
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
0

This is how operators work in Java. If you have any arithmetic operation, say division, in which both operands are integer then the operator will yield an integer. It is possible to loose some information in such division operations.

In your case, though you are assigning the result to a variable of type double, the assignment operator is executed after division operator is finished.

If you do not want to loose information, you can typecast any of the operand to desired type (in your case, to double).

avg = (double)(a + b + c) / 3;

Or

avg = (a + b + c) / (double)3;

Now, in above statements, division operator has two operands of different types. So the result will of type which is superior among the two.

Yogesh Ralebhat
  • 1,376
  • 1
  • 13
  • 29