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..

1

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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

Comments

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;

Comments

0

Use the foloving cast to at least one operand to double

itf=((double)a)/b;

or

itf=a/((double)b);

Comments

0
double itf = ((double) a / (double) b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.