This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Program 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
Program 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'
Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).
Am I wrong? I encourage you to correct me! This is how I learn.. :)
In your first example:
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you've already lost all information to the right of the decimal point.
Try some casting.
int sum = 30;
double avg = (double) sum / 4; // result is 7.5
OR
int sum = 30;
double avg = sum / 4.0d; // result is 7.5
This is an integer division (because it involves two integers)
int sum = 30;
double avg = (sum / 4); // result is 7
Integer division, will round down to the nearest integer.
However, this is a double division (because 4.0 is a double)
int sum= 30
double avg = (sum/4.0) // result is 7.5
This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.
A widening conversion of an int or a long value to float, or of a long
value to double, may result in loss of precision - that is, the result
may lose some of the least significant bits of the value. In this
case, the resulting floating-point value will be a correctly rounded
version of the integer value, using IEEE 754 round-to-nearest mode
In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions.
Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
But if you try either 30.0/4 or 30/4.0 then the result will be 7.5 because you will be using floating-point division.
The declared type of the variable avg has no influence on the result. The decimal part is lost during the division, and not when you assign the value to the variable.
Image taken from : http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
Refer above URL for more clear explanation.
PROGRAM 1
In Java, when you do a division between two integers, the result is an integer. So when you do sum/4, the result is the integer 7. Then you assign that integer to a double variable, so that 7 turns into 7.0.
PROGRAM 2
In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5. Then you assign that to a double variable, so it's still 7.5.
So the problem is not how println prints the variables, but how division works in Java
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Dividing two integers in Java gives me 0 or 100?
(5 answers)
Closed 9 years ago.
OK so this is a problem in a larger piece of code which does'nt seem to make sense. below is the code which is the problem... It prints Ratio = 0.0 the console when launched it should be equal to ~0,348.
public class MathTest {
public static void main(String[] args) {
double ratio = 29511 / 84812;
System.out.println("Ratio = "+ ratio);
}
}
Edit:
What if the code is this:
public class MathTest {
public static void main(String[] args) {
int int1 = 7;
int int2 = 13;
double double1 = int1/int2;
System.out.println("double1 = "+ double1);
}
}
It again prints "0.0".
You have unwittingly used integer division when you say 29511 / 84812, which in Java, loses the decimal points. Use double literals (with .0 added) instead:
double ratio = 29511.0 / 84812.0;
Other solutions that work here:
Cast one of them to a double: (double) 29511 / 84812
Use 'D' as another way to indicate a Java double literal: 29511D / 84812D
You are doing integer division because 29511 and 84812 are ints. The result of the division is 0, and you are saving it as a double so it becomes 0.0.
To fix this, cast one of the operands on the right side of the assignment to a double.
double ratio = (double)29511 / 84812;
Replace double ratio = 29511 / 84812 with double ratio = 29511.0 / 84812.0;
It make perfect sense. You are dividing two integers to get an integer. This means 0 in this case.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.
To work around this, you should (as many others have suggested) instead calculate the quotient of
(the double 3) / (the double 2)
or, in Java syntax,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial from Oracle
Integer division of 3 by 2 is equal to 1 with residue of 1. Casting to double gives 1.0
3 and 2 are integer constants and therefore 3 / 2 is an integer division which results in 1 which is then cast into a double. You want 3.0 / 2.0
Try: double wang = 3.0 / 2.0;
That's the expected behaviour. "3" and "2" are both int values, and when you perform 3 / 2 the result will also be an int value which gets rounded down to 1. if you cast both to double before you perform the division then you'll get the result that you expect:
double wang = (double)3 / (double)2;