开发者

Java int vs. Double

public double calc(int v1) {
return v1 / 2 + 1.5;
}


public double cald (double v) {
return v / 2 + 1.5;
}

Do the functions return the same result?

I would argue that they don't return开发者_运维知识库 the same result, as the second function would include the decimal point, where as the second function would round the number up.

Is that correct?


when you divide a by b i.e a/b

if both a & b are int then result will be int
else any or both a & b are double then result will be double

Edit:

Also see my answer to this Question Simple Divide Problem


They don't: see sample on IDEONE, clone it and play with it.

System.out.println(calc(1));// gives 1.5
System.out.println(cald(1.0));// gives 2.0


int v1 = 1;
return v1 / 2 + 1.5; // = 1.5

it is an integer divided by an integer more double. Or in your case 1 / 2, that it is 0.5, but it is a division amoung ints, so will be 0, more 1.5, return 1.5.

double v = 1.0;
return v / 2 + 1.5; // = 2.0

This case, the division is between an double and an int, returning an double of value 0.5, summing with 1.5 will return 2.0.


They don't return the same. / on default is integer division if the numbers are integers, i.e., the result of a/2 is an integer without the reminder if a is an integer. while if a is a double, then the result of this division is a double.

5/2 = 2
5.0/2 = 2.5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜