P
P
PRAIT2019-07-13 11:40:31
Java
PRAIT, 2019-07-13 11:40:31

How to cast an integer to double and then divide it?

Hi guys. I have a task to write a simple calculator that counts two numbers.

package Dz;
import java.util.Scanner;
public class SimpleCalculator {
  public static void main(String[] args) {
    try(Scanner dev = new Scanner(System.in)) {
      int a, b, c, max, min;
      double e;
      System.out.println("Pleasee enter number A");
      a = dev.nextInt();
      System.out.println("Pleasee enter number B");
      b = dev.nextInt();
      System.out.println("a = "+a);
      System.out.println("b = "+b);
      c = a + b;
      System.out.println("a + b = "+c);
      c = a - b;
      System.out.println("a - b = "+c);
      c = a * b;
      System.out.println("a * b = " +c);
      c = a / b;
      System.out.println("a/b = " +e); // double
      e = a / b; //double
      System.out.println("a / b = " +c);
      c = a % b;
      System.out.println("a % b = " +c);
      c = a ^ b;
      System.out.println("a ^ b = " +c);
    }
  }
}

It seems to be nothing complicated, but I can’t bring the type double 21 - 22 lines in the code. The compiler swears, can anyone tell me what's wrong? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Frozen Coder, 2019-07-13
@PRAIT

System.out.println("a/b = " +e); // double

You are trying to display an uninitialized variable, which the compiler should tell you in English. Read his messages. Print c first, then e.
If you want to get the result of division with a fractional part, then you must explicitly cast one of the division arguments to double. For example, the result of dividing an int by an int will be int, which means that the fractional part will simply be discarded even without rounding. Therefore, even if you store the result of such a division in double, then you will get 0 in the fractional part. If one of the arguments when dividing is double, then the result will be double with a fractional part. PS Please take any java textbook and read it. Read what the compiler tells you. By following these two simple tips, the number of questions will be kept to a minimum.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question