Organizational Research By

Surprising Reserch Topic

why double width 50 110000 the output is 0 000000000000000


why double width 50 110000 the output is 0 000000000000000  using -'java'

This is my code :

double width = 50/110000;
System.out.println("width ori is "+width );


And the output is: 0.00000000000

What's wrong ? the expected output has to be 4.5454545454545455E-4

Any body can explain to me why?
    

asked Sep 24, 2015 by rajnipancholi
0 votes
1 view



Related Hot Questions

3 Answers

0 votes

Because you're dividing two integers, so it will only take the integer part (integer division).

Dividing integers in a computer program requires special care. Some programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.

Examples :

In real life                  In Java

4/3  = 1.33333                4/3  = 1
25/12 = 2.083333              25/12 = 2
9/2 = 4.5                     9/2 = 4
50/110000 = 0.000454545       50/110000 = 0

You can cast one of the number (or both but it's actually useless) to double to avoid that :

double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
answered Sep 24, 2015 by santosh soni
0 votes

Explanation to what's happening:

In Java, the default type of numbers is int, so when you write 50/110000, they're both considered int, although you defined the result to be double.
When int division occurs, the result will be 0, because they are both ints, then the double will hold this value, which will be represented as double, so you're getting 0.000000.

Possible solutions:

  • Coding these numbers with d: 50d/110000d.
  • Casting one side explicitly (the other will be implicitly cast): (double)50/110000.
  • 50.0/110000.

See Chapter 5. Conversions and Promotions, it'll really help you.

answered Sep 24, 2015 by rajesh
0 votes

Result of int/int returns you an integer.

So the decimal part got truncated resulting you with an integer

You need to cast:

double width = (double)50/110000;

As @Josh M has pointed, You can also try :

double width = 50d / 110000d;
answered Sep 24, 2015 by virendra.bajaj

...