deadstarZZZ
deadstarZZZ

Reputation: 1

How to get the actual average, not rounded?

this is what I have (changed the print message for this question), and when I do 4 and 11, you should get 7.5, but it's only giving me 7. how do I fix this?

import java.util.Scanner;

class U1_L6_Average_Finder {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int a;
    int b;
    System.out.println("put in 4");
    a = scan.nextInt();
    System.out.println("Put in 11");
    b = scan.nextInt();
    System.out.println("Here is your average");
    System.out.print((a + b) / 2);
}

Upvotes: 0

Views: 170

Answers (4)

user7583349
user7583349

Reputation:

You are using integer divison. Integer divison will result integer as answer. You have to change one of the values to double.

Example:

System.out.println((double)(a+b)/2);

or

System.out.println((a+b)/2.0));

Upvotes: 0

JGFMK
JGFMK

Reputation: 8904

  • You have the input/averaging nailed. So here's the missing bit.
  • Just output r...
  • But if you want a certain number of decimal places (5 here)...
  • I did this in case you wanted to average more than 2 items...

import java.text.DecimalFormat;
class Playground {
    public static void main(String[ ] args) {
        int i = 5;
        int j = 17;
        double r = (double)i/j;
        DecimalFormat df = new DecimalFormat("#.#####");
        System.out.println(r);
        System.out.println(df.format(r));
    }
}

Outputs:

0.29411764705882354

0.29412

Upvotes: 0

devs121
devs121

Reputation: 59

You're using integers (int a, b;), so it will round your results.

Instead of it, use double or float to get what you want, e.g: double a, b;

But, if you don't want to modify the type of your variable, you can edit your last System.out.print using f (for example), that will convert your value to float, e.g:

System.out.print((a + b) / 2.0f);

Check this to understand more about variables: Java Variables

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

You could coerce the quotient to a floating-point value by changing the 2 (denominator) to a 2.0, 2f, 2.0f. If you want a double, you can use a d instead of an f.

public class AverageFloatingPointCoercionExample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a, b;

        System.out.print("Enter value #1 (4): ");
        a = scan.nextInt();

        System.out.print("Enter value #2 (11): ");
        b = scan.nextInt();

        System.out.print("Here is your average: ");
        System.out.print((a + b) / 2.0f); // 7.5
    }
}

Alternatively, you can cast the numerator explicitly.

System.out.print(((float) (a + b)) / 2);

Upvotes: 1

Related Questions