0

It's been a long day for me and I don't know if I can't do second grade math or if I'm doing something wrong in terms of how to do math in java. I'm not new to java, I started about a year and a half ago, but like I said, it's been a long day.

Here is my code:

System.out.println(5 / 150 * 100);

I expect to get something like "3.3333" or at least "3", but I get "0" instead. Why is that and how do I fix it?

Hades948
  • 21
  • 6

2 Answers2

1

Your second grade math is perfectly correct. However, 5 / 150 = 0.03 will become zero because its type is int. Then multiplying 0 with 100 won't change anything.

Use floats or doubles and you'll get the right result. Which of these two you use, depends on your needs. If you need a very precise value (a freaking lot of 3s behind the point) use double because it has - as its name tells you - two times the precision of a float.

Marco
  • 330
  • 3
  • 12
-1

All of your operand is int value and it will result in int value.

Try to change your operand to float value.

Try this:

System.out.println(5f / 150 * 100);
System.out.println(5 / 150f * 100);
Iswanto San
  • 18,263
  • 13
  • 58
  • 79