0

I am new to Java. I wrote this easy program but for some reason even though I am using the conversion specifier %f for float, the quotient ( division calculation ) is returning the result in the command window as 0.000000. Why is this not calculating correctly? Below is the question I wrote the program to answer.

/* 2.15 (Arithmetic) Write an application that asks the user to enter two integers, obtains them from the user and prints their sum, product, difference and quotient (division). Use the techniques shown in Fig. 2.7. */

import java.util.Scanner;

public class Main 
{
  public static void main ( String [] args )
  {
    Scanner input = new Scanner (System.in);

    int a;
    int b;

    int sum;
    int product;
    int difference;
    float quotient;

    System.out.println( "Enter the first integer: ");
    a = input.nextInt();

    System.out.println( "Enter the second integer: ");
    b = input.nextInt();

    sum = a + b;
    System.out.printf( "The sum is %d.%n", sum );

    product = a * b;
    System.out.printf( "The product is %d.%n", product );

    difference = a - b;
    System.out.printf ( "The difference is %d.%n", difference );

    quotient = a / b;

    System.out.printf ( "The quotient is %f.%n", quotient );
  }
}
Milansan
  • 11
  • 1
  • 2
  • I assume you entered `a` value less than `b` value. `a / b` is integer divide, yielding 0. That 0 is then converted to `float` when assigned to `quotient`. So printing `%f` gives `0.000000`. Try `quotient = (float)a / b;`. – lurker Jan 25 '18 at 17:54
  • you need to change a or b from int to float (or double), if both are int than the result of a/b will be an integer. For example if a=1, b=2 then a/b = 0 instead of 0.5 – seiya Jan 25 '18 at 17:55

0 Answers0