Java Why is this giving me "0"? [duplicate] - java

This question already has answers here:
Why does the division of two integers return 0.0 in Java? [duplicate]
(6 answers)
Closed 8 years ago.
So this is a portion of the code I'm using, we were only supposed to begin by fixing some logical errors because of wrong answers. I found a couple of syntax errors as well that wouldn't let the compiler finish up...I keep getting "0" for fToC...
//declaration statements
final int BOILING_IN_F = 212;
int fToC;
string output;
//there is other code between that has nothing
//to do with outputting the boiling point.
fToC = (5/9) * (BOILING_IN_F - 32);
output = BOILING_IN_F + " in Fahrenheit is " + fToC
+ " in Celsius.";
System.out.println(output); //this is outputting 0 for fToC
System.out.println();
Answers were useful, except I needed to declare fToC as a double before compiling and running the program. Thank you.

You are performing Java's integer division with 5/9, which must result in another integer -- 0, so the result is 0. Use double literals to force floating-point math.
fToC = (5.0/9.0) * (BOILING_IN_F - 32);
You'll need fToC to be a double (and change the typo string output to be String output).

(5/9) is 0 due to int division. Try (5.0/9)
The full expression should be :
fToC = (5.0/9) * (BOILING_IN_F - 32);

(5/9) You're diving two integers, so this is truncated, so it equals 0. And you're multiplying that 0 with another number.
Use instead (5.0f/9.0f) to precise the fact that your number are actually decimal numbers.

Related

Why a double division is returning a very wrong value? [duplicate]

This question already has answers here:
How do I print a double value without scientific notation using Java?
(18 answers)
Closed 1 year ago.
this code below is return a very strange result. It should return 0.0008, but is return 8.202154101077051E-4. Can anyone help me to solve this?
double d1 = 0.0099;
double d2 = 12.0700;
double d3 = d1/d2;
System.out.println(d3);
Explanation
It should return 0.0008
It does.
"E" is a format for numbers that are either very big or very close to 0. If an E(value) stands behind a number, that basically means "take this number and multiply it by 10 ^ value".
If you take 8.202154101077051 x 10 ^ -4, you will get 0.0008202154101077051, which is approximatly 0.0008.
Solution
How you can format numbers when printing them out is explained in this stackoverflow answer.

Why is my implementation of math.random in my class only returning 0? [duplicate]

This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 2 years ago.
I've been trying to create a class to roll dice for games, and my code for one aspect of it is:
public int[] yahtzeeRoll() {
int[] rolls1 = new int[6];
for (int i = 0; i < 6; i++) {
rolls1[i] = ((int) Math.random()*6+1);
}
return rolls1;
}
yet, when I call it in the main method, it only returns 1 for each of the values. Why is this? How can I fix my code so that it generates 6 different numbers when I print the array in the main method?
You are casting the double value returned by Math.random() to int before multiplying by 6, and since Math.random() returns a value < 1, casting it to int results in 0.
Change
rolls1[i] = ((int) Math.random()*6+1);
to
rolls1[i] = (int)(Math.random()*6)+1;
The type casting by appending (type) takes precedence over the * 6 bits afterwards. Therefore, the result from Math.random() is always casted into 0 before you multiply it by 6, which turns out to always be 0 as well.
This answer points to this site which explains it quite well.
Either (int) (Math.random() * 6) + 1 or (int) (Math.random() * 6 + 1) would work as you have intended.
Math.random returns a floating point number between 0 and 1 but you are truncating it down to 0 by using (int) type cast before it. Use parentheses around your expression and then prepend (int) to that if you do wish to use integer truncation.
Btw, I think same sequence should be generated at each run if you don't seed the pseudo-random engine, say with current time or something.
Let's look at the expression.
((int) Math.random()*6+1)
Now Math.random() returns a double that is >=0 and <1.
You then cast that result to an int which means it will always become 0.
If you use.
(int)(Math.random()*6+1)
You are taking the double between 0 and 1, multiplying it by 6 (giving 0 ... 6) adding 1 and then casting to an int. This looks more like what you are looking for.
Math.random() returns double value in range [0, 1) (greater than or equal to 0.0 and less than 1.0). Then you cast that double value to int, so it always results in 0. After that you add 1 to it, so the result always remains 1.
You should cast result of multiplication - Math.random() * 6 instead of casting Math.random() return value:
rolls1[i] = (int)(Math.random()*6)+1;
By the way, you should be aware of operators precedence in Java language. You can have a look here: operator precedence to see nice table that shows that casting has a higher priority than multiplication and addition - this is the reason, why (Math.random()*6) is put in parenthesis for casting (this way you avoid casting only Math.random())
PS. There is also a link to table of operator precedence in official Java tutorial, but it doesn't exactly fit to your problem as it doesn't contain operation of casting - this is the reason, why I provided another link firstly.
You can take a clue from the below output presentation which is self explanatory.
Code:
double random = Math.random();
System.out.println("Math.random()>>"+random);
System.out.println("Math.random()*6>>"+random*6);
System.out.println("(int)(Math.random()*6)>>"+(int)(random*6));
System.out.println("Math.random()*6+1>>"+random*6+1); //+1 here is treated as a string by java and will add at the end of the number
System.out.println("(Math.random()*6+1)>>"+(random*6+1)); //number random*6 will be incremented by 1 as enclosing () will treat them as numbers
System.out.println("(int)(Math.random()*6+1)>>"+(int)(random*6+1));
Output:
Math.random()>>0.6793602796545469
Math.random()*6>>4.076161677927281
(int)(Math.random()*6)>>4
Math.random()*6+1>>4.0761616779272811
(Math.random()*6+1)>>5.076161677927281
(int)(Math.random()*6+1)>>5

Java Double Division Returning 0; Math Checks Out IRL [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 5 years ago.
I am writing a very simple Fahrenheit to Celsius conversion program that takes a named constant and converts it to Celsius via a simple calculation of (constant - 32) * (5/9)
for whatever reason whenever I run this program it returns 0.0 for Celcius. The math checks out in real life, and the answer is 100, but for whatever reason I keep getting 0.0 from the program. Here's the code:
final double BOILING_IN_F = 212; // Boiling temperature
double fToC; // Temperature Celsius
fToC = (BOILING_IN_F - 32) * (5/9);
output = BOILING_IN_F + " in Fahrenheit is " + fToC + " in Celsius.";
System.out.println(output);
I know that when dividing integers, any fractional number will be returned as a whole, which is why I changed my variables to double. Even still, it returns 0. I also tried using float as my data type and switching around the calculation while adding (irrelevant) parentheses.
5/9 evaluates to 0 since 0.5555555556 rounded towards 0 is 0, which happens because you're using integer division. Change one of the integers to a floating number:
5 / 9.0
If both numbers are integers, it uses integer division which truncates the result. One of the operands must be a non-integer to use non-integer division.
Replace
5/9 with 5.0/9.0. This will make sure you get proper division. 5/9 = 0 while 5.0/9.0 = 0.555...
(5/9) is integer division, resulting in 0.

Rounding off 2 decimal places in Java for whole number [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have the following and the question is, for example if zzi = 95 then myNum will be correctly displayed as 32.33, exactly as I want it too with two decimal places.
However if zzi = 94, myNum will be displayed as 32.0 instead of 32.00
How to display it as 32.00?
float xFunction(int zzi) {
float myNum = (zzi + 2);
myNum = myNum / 3;
int precision = 100; // keep 4 digits
myNum = (float) (Math.floor(myNum * precision + .5) / precision);
return myNum;
}
Thanks before.
Your question is not so much about rounding a number as it is about rounding a display or String representation of a number. The solution:
Use new DecimalFormat("0.00");
Or String.format("%.2f", myNumber);
Or new java.util.Formatter("%.2f", myNumber);
Or System.out.printf("%.2f", myNumber);
Note: avoid use of float whenever possible, and instead prefer use of double which greatly improves numeric precision at little cost. For financial calculations use neither but instead opt for integer calculations or use BigDecimal.
Remember:
1) printing the number displaying two decimal places is very different from rounding the actual value. In other words "representation" != actual value.
2) floating point values are always imprecise. Even with rounding, you may or may not get an "exact value".
Having said that, the simplest approach is:
float myNum = ((123.456 * 100.0) + .5) / 100.0;
new DecimalFormat("#.##").format(myNum );
You can use DecimalFormat
System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
You should work on the printing function. I assume you are using a System.out.println: replace it with
System.out.format("%.2f", numberToPrint);
Read the docs for that function to discover more about format strings.

Why does the division of two integers return 0.0 in Java? [duplicate]

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) + "%"));

Categories

Resources