+ 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); } }
3 Answers
+ 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 š
+ 5
Just a simple change required.
double divd = (double)y/x.
+ 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;