我想我需要转换这个代码。我需要返回一个整数,但我必须乘以百分数,并且不希望它们被截断。
我应该像这样转换brains = (double)brains - (this.getBrains() * 0.01);吗?
另外,我应该在结尾处转换返回语句吗?我在选角方面很弱,我一直在努力寻找有帮助的例子,但他们没有帮助。
if(attacker >= attackee)
{
switch (weapon)
{
case 't':
brains = brains + (other.getBrains() * 0.01);
attack = other.getBrains() * -0.01;
other.addBrains(attack);
break;
case 's':
brains = brains + (other.getBrains() * 0.05);
attack = other.getBrains() * -0.05;
other.addBrains(attack);
break;
case 'c':
brains = brains + (other.getBrains() * 0.10);
attack = other.getBrains() * -0.10;
other.addBrains(attack);
break;
case 'k':
brains = brains + (other.getBrains() * 0.20);
attack = other.getBrains() * -0.20;
other.addBrains(attack);
break;
}
}
else
{
switch (weapon)
{
case 't':
brains = brains - (this.getBrains() * 0.01);
attack = this.getBrains() * 0.01;
other.addBrains(attack);
break;
case 's':
brains = brains - (this.getBrains() * 0.01);
attack = this.getBrains() * 0.01;
other.addBrains(attack);
break;
case 'c':
brains = brains - (this.getBrains() * 0.01);
attack = this.getBrains() * 0.01;
other.addBrains(attack);
break;
case 'k':
brains = brains - (this.getBrains() * 0.01);
attack = this.getBrains() * 0.01;
other.addBrains(attack);
break;
}
}
return attack;
}发布于 2013-11-12 07:58:11
从double到int的强制转换将始终截断,因此可能不是您想要的。也就是说,(int)3.812会给你3,当你想要4的时候。
您也不需要强制转换为double,因为"int + int * double“将返回一个double。
最简单的方法是使用Math.round,它会向上舍入较大的值。请注意,双精度舍入为长整型,而浮点型为整型。
Floats几乎肯定会给你提供你想要的精度,所以对你来说最简单的解决方案是:
brains = Math.round(brains - this.getBrains() * 0.01f);编辑整数:如果你确实想要比双精度更高的精度,那么Math.round会给你一个长整型,你需要将它转换成一个整型:
brains = (int)Math.round(brains - this.getBrains() * 0.01d); 请注意,常量已从0.01f更改为0.01d,从而更改了整个计算的精度。
发布于 2013-11-12 07:56:53
假设你想要减去100%的大脑。您可以通过不同的方式来完成此操作:
四舍五入:brains = brains - (this.getBrains() / 100);
brains = brains - (int)((double)this.getBrains() * 0.01 + 0.5);当然,第一种方法总是可以通过强制转换来完成,我不确定两次强制转换是比整数除法更快还是更慢。
由于attack是一个整数,返回值也是,所以不需要对返回值进行强制转换。
发布于 2013-11-12 08:01:48
如果同一表达式中有较大的数据类型,Java会自动提升较小的数据类型。如果您这样做:
brains = brains + (other.getBrains() * 0.01);您根本不需要显式强制转换为双精度型,因为0.01是双精度型,表达式的这一部分将首先计算(带括号的/乘法)。如果brains是一个整数,则需要将表达式转换回整数才能进行赋值。如下所示:
brains = (int)Math.rint(brains + (other.getBrains() * 0.01));当然,请确保您的整数不小(对于您正在执行的操作,小于100 )。
https://stackoverflow.com/questions/19918191
复制相似问题