0
int a = 1;
int b = 10;
int c = 3;

int d = (1/10)*3

System.out.println(d)

Result: 0

How do i make this Calculation work ? and round up or down ? It should be: (1/10)*3 = 0.1 * 3 = 0.3 = 0 and (4/10)*3 = 0.4 * 3 = 1.2 = 1

Thanks a lot!

1
  • 2
    OP, please accept your answer instead of adding a message to the question. Click the grey checkmark to the left of the answer. This signals to everyone that the question is indeed answered and you are satisfied with the answer. Commented Aug 24, 2012 at 9:26

7 Answers 7

5
1 / 10

This is integer division and as integer division the result is 0. Then 0 * 3 = 0

You can use double literals:

1.0 / 10.0
Sign up to request clarification or add additional context in comments.

2 Comments

Those are floats. To specify double append a D.
@SteveKuo: no, floating-point literals are double by default. It's only a float if you suffix it with F (or f).
1

Try:

int d = (int) (((double)4/10)*3);

Comments

1

1/10

This line return 0.so 0*3=0.Use double instead of int

2 Comments

And then cast it back, or round it to int, if you need to.
This won't work - 1/10 is still integer division, so the result is 0 again (of type double)
0

as both a and b are integer so the output will also be int which makes 1/10 as 0 and then 0*3=0

Comments

0

You will want to perform the calculation using floating-point representation. Then you can cast the result back to an integer.

Comments

0

I note that you refer in your question to rounding up/down.

Math.round() will help you here.

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long.

Comments

0

This will works

int a = 1;
int b = 10;
int c = 3;    
int d = (1*3/10);    
System.out.println(d);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.