This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
I have the following method in a Java program:
public void Div(int a, int b){
//exception in order to check if the second argument is 0
try{
int div1 = (a / b);
double div = div1;
System.out.println("The division of the two numbers is: " + div);
}
catch(ArithmeticException e){
System.out.println("You can't divide a number by 0");
}
This only works if numerator is larger than the denominator ( e.g 8/2). If the numerator is smaller than the denominator I get a result of 0.0 (e.g. 2/8).
What can I do to make it work?
It's happening because of integer division. You can cast one of the arguments to double and store the result to a double variable to fix the issue.
public class Main {
public static void main(String[] args) {
div(5, 10);
}
public static void div(int a, int b) {
try {
double div = (double) a / b;
System.out.println("The division of the two numbers is: " + div);
} catch (ArithmeticException e) {
System.out.println("You can't divide a number by 0");
}
}
}
Output:
The division of the two numbers is: 0.5
On a side note, you should follow Java naming conventions e.g. the method name, Div should be div as per the Java naming conventions.
(a/b) You're doing integer division. You need to typecast to other data types that can store decimal like double.
double div = (double) a / b;
Related
This question already has answers here:
How to avoid floating point precision errors with floats or doubles in Java?
(12 answers)
Closed 5 years ago.
I have the following code.
public class ToBeDeleted {
public static final float MAX_PHYSICAL_LENGTH = 100000000;
public static void main(String[] args) {
//100000000
float temp = 100000000 -4;
System.out.println(temp);
if (MAX_PHYSICAL_LENGTH == temp)
System.out.println("True statement");
else
System.out.println("False Statement");
}
}
The output of the above is
1.0E8
True statement
Now with the below code
public class ToBeDeleted {
public static final float MAX_PHYSICAL_LENGTH = 100000000;
public static void main(String[] args) {
//100000000
float temp = 100000000 -5;
System.out.println(temp);
if (MAX_PHYSICAL_LENGTH == temp)
System.out.println("True statement");
else
System.out.println("False Statement");
}
}
The output is
9.9999992E7
False Statement
The question is
Whats wrong with the first code snip. Is this not plain mathematics
as far as float is concerned?
Why does it then give the expected output on the second code snip.
A typical (i.e. IEEE754) float only has 23 bits of precision. The other bits are for the exponent and the sign. The lowest integer that you can't store exactly is 1 plus the 24th power of 2.
100000000 - 4 is indistinguishable from 100000000 - 0.
A Java double gives you 52 bits of precision, therefore enough space to store all integers exactly up to the 53rd power of 2.
For more details see Which is the first integer that an IEEE 754 float is incapable of representing exactly?
But if you need exact decimal accuracy, then use a decimal type.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
/**
* Write a description of class GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
public class GUI
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner r = new Scanner(System.in);
int x;
int y;
int z;
System.out.println("x");
x = r.nextInt();
System.out.println("y");
y = r.nextInt();
System.out.println("z");
z = r.nextInt();
double t = (x+y+z)/3;
System.out.println("result " + t);
}
}
Hello, above is my code.
I purposely made it int x,y,z to test the program.
When I input for example (when running the program) :$x = 1, 1, 3$ it rounds the answer always! Why is this?
This is an example of Java's integer division, which must always return another integer. It truncates any decimal result. This occurs even though the result is assigned to a double.
Use a double literal when dividing to force floating-point division.
double t = (x+y+z)/3.0;
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
My code:
public class Test {
public static int l = 29;
public static int w = 16;
public static int total = w + l;
public static int result = w / total;
public static int Result = total * 100;
public static void main(String[] args) {
System.out.println("You're W/L ratio is: " + (Result) + "%"); // Display the string.
}
}
Response in console: You're W/L ratio is: 0%
You're doing int division which always returns an int and so w / total will always be 0 since total is always greater than w. Do the multiplication by 100 first.
int result = (w * 100) / total;
Also you will want to learn and use java naming rules. Variable names should begin with a lower case letter.
Do the calculation by casting w and total to double, or just make them double to begin with. For the first option:
public static double result = (double)w / (double)total;
whenever you do division when both numbers are integers, in result you will get integer in return.
which actually means you will get floor value of (a/b); ie:
1/2=0 as 1/2=> 0.5> floor of 0.5= 0;
3/4=0 as 3/4=> 0.75> floor of 0.75= 0;
etc
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
I have tried this in Javascript and have gotten my answers, but the answer I need must be more exact. I am trying to divide 1 by every number between 2 and 1000, and simply print them.
public static void main(String [] args) {
for (int i=2;i<=1000;i++){
double g = (1/i);
System.out.println(g); // print "1/1,2,3,4.....1000"
}
}
I haven't done Java in a while, so I forget my correct variable names.
Since both 1 and i are integers, integer division is being used. Either 1 or i need to be double in the 1/i section of your code so that integer division is not used. You can do something like 1.0/i or 1/((double) i) to ensure that float division is used instead.
replace 1 by 1.0D that will result into double
try this
public static void main ( String args[] ) {
for (int i=2;i<=1000;i++){
double g = (1.0/i);
System.out.println("1/"+ig);
}
output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
.
.
.
.
I would do something like this (note you can have as many digits of precision as you like) utilizing BigDecimal.
public static void main(String[] args) {
java.math.BigDecimal ONE = java.math.BigDecimal.ONE;
// 50 digits of precision.
java.math.MathContext mc = new java.math.MathContext(50);
for (int i = 2; i <= 1000; i++) {
java.math.BigDecimal divisor = new java.math.BigDecimal(i);
java.math.BigDecimal result = ONE.divide(divisor, mc);
result.round(mc);
System.out.printf("%d/%d = %s\n", 1, i,
result.toString());
}
}
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 5 years ago.
import java.util.Scanner;
public class test {
private static int number1 = 100;
private static int number2 = 1;
public static double avgAge() {
return (number1 + number2) / 2;
}
public static void main(String[] args) {
System.out.println("Average number: " + test.avgAge());
}
}
Why does test.avgAge() = 50.0 instead of 50.5? Is there a way to output 50.5 instead?
The calculation is done as an integer calculation.
If you replace 2 by 2.0 you will get 50.5. I recommend adding a comment to that line to explain this to future readers.
Alternatively you can explicitly cast to a double:
((double) (number1 + number2)) / 2
Just replace this function
import java.util.Scanner;
public class test {
private static int number1 = 100;
private static int number2 = 1;
public static double avgAge() {
return (number1 + number2) / 2.0;
}
public static void main(String[] args) {
System.out.println("Average number: " + test.avgAge()); //Average number: 50.5
}
}
It's because you're using ints through out the calculation before returning it as a double. Do the following:
private static double number1 = 100.0;
private static double number2 = 1.0;
Change these to double. Also, change the 2 to 2.0:
return (number1 + number2) / 2.0;
Read more about ints and doubles here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
That's because of type promotion.
If in an operation, any of the operands is a double, then the result is promoted to double.
Since here all operands are ints, the division results in an int.
Type Promotion
return ((double)(number1 + number2)) / 2;