数据库单元格值的计算
我有一个带有表的数据库,其中包含两个整数字段。
当我尝试获取百分比 (fieldA / (fieldA+fieldB)) 时,该值为 0。
double percentage = fieldA+fieldB // WORKS; 5+5=10
double percentage = fieldA / (fieldA+fieldB) // DOES NOT WORK; 5+5=0
那么这里有什么问题呢?谢谢..
I have a database with a table, containing two integer fields.
When I try to get a percentage (fieldA / (fieldA+fieldB)), the value is 0.
double percentage = fieldA+fieldB // WORKS; 5+5=10
double percentage = fieldA / (fieldA+fieldB) // DOES NOT WORK; 5+5=0
So what's the problem here? Thanks..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当您执行
fieldA / (fieldA+fieldB)
时,您会得到 5/10,作为整数,它会被截断为 0,如果您想要结果为 0.5,则必须进行双除。即像这样:
When you do
fieldA / (fieldA+fieldB)
you get 5/10, which as an integer is truncated to 0, you have to do double division if you want 0.5 as a result.i.e. something like this:
我确实假设
fieldA
和fieldB
是整数?如果是,您应该知道,无论等式左边是什么,两个整数相除也会得到一个整数。因此,将
fieldA
除以(fieldA+fieldB)
会得到一个值(fieldA+fieldB)
。 1 结果为零。请参阅 Wikipedia 上的整数除法。要解决此问题,只需将至少一个操作数转换为浮点类型,例如:
I do assume
fieldA
andfieldB
are integers? If yes, you should be aware that dividing two integers results in an integer, too, no matter what is on the left side of the equation.So dividing
fieldA
by(fieldA+fieldB)
results in a value < 1 which results in zero. See Integer Division on Wikipedia.To correct the issue, simply cast at least one operand to a floating point type like e.g.:
由于 fieldA 和 fieldB 是整数,因此表达式
fieldA / (fieldA+fieldB)
的形式为int / int
,这意味着您将使用整数除法,在本例中 - < code>5/10 = 0,因为整数除法求解x = am + b
,在本例中5 = a*10 + b
这意味着 <代码>a = 0, b = 5但是您可以这样做:
Since fieldA and fieldB are integers, the expression
fieldA / (fieldA+fieldB)
is of the formint / int
which means you will use integer division, in this case -5/10 = 0
, as integer division solvesx = am + b
, and in this case5 = a*10 + b
which meansa = 0, b = 5
You can do however:
在应用操作之前,您可能需要将字段转换为双精度型
You may need to cast the fields as doubles before applying the operation
试试这个:双倍百分比 = (双)fieldA/(double)(fieldA+fieldB)
try this : double percentage = (double)fieldA/(double)(fieldA+fieldB)
如果两个字段都是整数,则两个整数相加的结果也是整数。
试试这个
浮点结果 = (float)((A*100)/(B+A));
答案:结果 = 50.0
if both fields are integer, then the addition of the two integer results also integer.
Try this
float result = (float)((A*100)/(B+A));
Answer: result = 50.0