简体   繁体   English

Java int与Double

[英]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 ie a/b 当您将a除以ba/b

if both a & b are int then result will be int 如果两个 abint然后结果将被int
else any or both a & b are double then result will be double 否则ab中的任何一个或两个都double则结果为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. 他们没有: 在IDEONE上查看示例,对其进行克隆并使用它。

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. 或者在您的情况1/2中,它是0.5,但它是一个整数除法,因此将是0,大于1.5,则返回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. 在这种情况下,除法在double和int之间,返回值0.5的double,与1.5相加将返回2.0。

They don't return the same. 他们不会返回相同的。 / on default is integer division if the numbers are integers, ie, the result of a/2 is an integer without the reminder if a is an integer. /如果数字是整数,则默认为整数除法,即, a/2的结果为整数,而a/2为整数则不作提示。 while if a is a double, then the result of this division is a double. 而如果a为双精度数,则该除法结果为双精度数。

5/2 = 2
5.0/2 = 2.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM