提问人:Kfir Arnesty 提问时间:11/4/2023 更新时间:11/4/2023 访问量:54
Android Math 似乎没有正确总结 [重复]
android math doesn't seem to sum up right [duplicate]
问:
我正在计算赢/输比,但是当我写 equason 时,不知何故它变成了零: 这是我的代码:
public void count() {
//int ratio = (wonCount/ (wonCount + lostCount)) * 100;
long ratio = 2/ (2 + 1) *100;
timesWon.setText("You Were Right " + wonCount + " Times");
timesLost.setText("You Were Wrong " + lostCount + " Times");
statistics.setText("Win/Loss Ratio: " + String.valueOf(ratio) + "%");
firstTime = false;
}
在 Java 中为 2/(2+1) *100 = 0。我错过了什么吗? 谢谢。
答:
0赞
alexedy
11/4/2023
#1
Java 首先进行除法,2 对 3 是一个十进制数,四舍五入后表示整数为 0。尝试使用浮点数据类型:
Double ratio = 2.0 / (2 + 1) *100;
-1赞
Reilas
11/4/2023
#2
"...当我写 equason 时,不知何故它变成了零......”
这是因为 2 除以 300 小于 1。
对每个带括号的除法运算至少使用 1 个浮点数值数据类型。
double ratio = ((double) wonCount/ (wonCount + lostCount)) * 100;
如果要查找下限值,请使用 Math#floor 方法。
long ratio = (long) Math.floor(((double) wonCount/ (wonCount + lostCount)) * 100);
评论
1赞
Sören
11/4/2023
但是没有人做 2 除以 300。
0赞
Reilas
11/4/2023
@Sören,这甚至没有意义。
1赞
Sören
11/4/2023
我应该把“2 除以 300”放在引号中。因为这是你回答中的一句话,所以与问题完全无关。问题是关于“2 除以 3”。
评论
2 / 3
0
2 / (2+1) * 100
(2 / (2+1) ) * 100
2 * 100 / (2+1)
(100 * wonCount) / (wonCount + lostCount)
)