+ 1

Why answer is not rational number?

In following program, why answer is not rational number? It is displaying answer in integer. What is wrong in this? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner yolo = new Scanner(System.in); System.out.println("Enter First Number: "); int x=yolo.nextInt(); System.out.println("Enter Second Number: "); int y=yolo.nextInt(); double divd=y/x; System.out.println("Division without remainder is:" + divd); } }

15th Jan 2018, 4:32 PM
Heramb Lonkar
Heramb Lonkar - avatar
3 Respostas
+ 24
in java , Integer/Integer gives an integer value only so here , y/x = Integer/Integer //here, decimal part gets chopped without any rounding off m1)take value of y&x as double only //u can give integer value also , bcz implicit type conversion don't need any typecasting & int value will get directly converted to a double value m2)double divd=(double)y/x; //typecasting int type to double type 😃
15th Jan 2018, 4:42 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Just a simple change required. double divd = (double)y/x.
15th Jan 2018, 4:38 PM
Hrishikesh Kulkarni
Hrishikesh Kulkarni - avatar
+ 3
When integers are divided, integer division takes place. Already after this, before assigning the resulting integer value, it is converted to double. Compare: double divd=(double)y/x;
15th Jan 2018, 4:43 PM
Вадим Сухотин (Vadim Sukhotin)
Вадим Сухотин (Vadim Sukhotin) - avatar