In: Computer Science
Java How to Program Exercise 4.11
Explain what happens when a Java program attempts to divide one
integer by another. What happens to the fractional part of the
calculation? How can you avoid that outcome?
My instructor want me to do that exercise with these details and I
am so confuse. I don't know where to start.
"Random number of Trips"
"Enter gallon and miles as whole numbers"
"NPG decimal number"
Java does integer division, as the regular real division, It
takes only the quotient and throw away the remainder.
Hence 4/3 gives 1.
However, if you don't want to lose the fractional part and want the result as float/double number, you need to type case any of the number of division to double.
So, division of 4.0/3 will give 1.333333333333 or double(4)/3 will result 1.333333333333
For the project , I guess, it is asking the user input from users as a whole number. and there by calculating NPG in decimal number. However about Random No of Trips, I am not sure. You ask in detail.
Below , I demonstrate this with some java code. Please check it
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int a = 8;
int b = 4;
int c = 3;
float d = b/c;
System.out.printf("a=%d b=%d
c=%d\n",a,b,c);
System.out.println("a/b : " +
(a/b));
System.out.println("b/c : " +
(b/c));
System.out.println("(double)b/c : "
+ (double)b/c);
System.out.println("b*1.0/c : "+
b*1.0/c);
Scanner in = new Scanner(System.in);
System.out.print("Enter Gallon in whole no: ");
int gallon = in.nextInt();
System.out.print("Enter Miles in whole no: ");
int mile = in.nextInt();
System.out.print("Mile per gallon is: " +
(double)mile/gallon);
}
}
It gives following output:
To get correct value of Miles /per gallon, you need to use double cast the numerator. You would get the result as 177, if you would simple do the division mile/gallon .
Hope this helps.
a=8 b=4 c=3 a/b : 2 b/c : 1 (double)b/c : 1.3333333333333333 b*1.0/c : 1.3333333333333333 Enter Gallon in whole no: 2 Enter Miles in whole no: 355 Mile per gallon is: 177.5