2

I have declared a variable as double. I wanted to do division of two integer and assign the output to that double variable.

But its not considering the values like 0.1 to 0.9. Only when the no is whole number like 4.0 its returning the answer

public static void main(String[] args) throws Exception
{
double itf=0;
a=4100;
b=6076  
itf=a/b;
System.out.println("itf:"+itf)
}

Output is itf: 0.0

Pls help..

user2828951
  • 21
  • 1
  • 3
  • Does this answer your question? [Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0) – Progman May 29 '21 at 17:52

6 Answers6

7

Most likely the variables a and b are defined as int , which will result in integer division result as 0 and when assigned to double it becomes 0.0. If you define a,b and itf as double then the result should be

0.6747860434496379 

instead of

 0.0

Try this code:

public static void main(String[] args) throws Exception {
    double itf = 0;
    double a = 4100;
    double b = 6076;
    itf = a / b;
    System.out.println("itf:" + itf);
}
Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123
2

a and b are both integers, so the result of a/b is also an integer, which is then cast to a double to be stored in itf. To get the correct result, you could either define a and b as doubles, or you could cast at least one of them to double. For instance:

itf = (double)a/b;
MrAzzaman
  • 4,674
  • 9
  • 24
2

Declare a or b as double.

OR Cast the operation.

itf = (double)(a/b)

OR Cast one of the integers.

itf = ((double)a)/b

OR multiply with 1.0, which is double.

itf = (1.0*a)/b
Sorter
  • 8,190
  • 5
  • 52
  • 63
0

The reason for your result is that you are using integer division, then assign the result to a double value. This is your code unrolled:

int a = 4100;
int b = 6076;
int temp = a / b;
double itf = temp;

If you want to explicitly use floating point division, you need to tell the compiler that you do by casting at least one (or all to be sure) member of that operation to double or float. Example:

itf = (double)a / (double)b;
TwoThe
  • 12,597
  • 3
  • 26
  • 50
0

Use the foloving cast to at least one operand to double

itf=((double)a)/b;

or

itf=a/((double)b);
0
double itf = ((double) a / (double) b);
Hanamant Jadhav
  • 101
  • 1
  • 5