【问题标题】:How can exact same value differ in math result only by changing type from int to decimal [duplicate]仅通过将类型从 int 更改为 decimal [重复]
【发布时间】:2021-04-01 07:18:35
【问题描述】:

我正在做一些项目,需要做一些数学运算:

decimal X = (Value / 881) * (item.Type ? 130: 130 * 2);

例如,参数“Value”等于 3000。

如果“值”的类型为 int,则结果为 390.. 如果“值”的类型为 decimal,则结果为 442.67

这怎么可能??

.NET Fiddle

【问题讨论】:

  • Valueint 类型时,您有整数除法Value / 8813000 / 881 == 3;当Valuedecimal 然后3000m / 881 == 3.405...m
  • int进行的不精确(例如产生余数的除法)操作越多,结果的累积误差就越大。

标签: c# integer decimal


【解决方案1】:

因为十进制值。如果您逐步计算公式,您将理解这种差异是由于使用 decimal 作为类型时的小数点后出现的值

当你将 3000(整数)除以 881 时:

int Value = 3000
//Output is 3. Output is in integer
decimal X = (Value / 881);  //When int is divided by int then result is in int

当你将 3000(十进制)除以 881 时:

decimal Value = 3000
//Output is 3.4052213393870601589103291714. Output is in decimal.
decimal X = (Value / 881);  //When decimal is divided by int then result is in decimal

.Net fiddle

我希望 .net fiddle 能让您更好地了解我的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2018-02-04
    • 2013-12-19
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多