【问题标题】:VB Script Integer division vs Float Division Rounding upVB脚本整数除法与浮点除法四舍五入
【发布时间】:2016-06-30 09:56:58
【问题描述】:

大家好,stackoverflowers,

我在将公式从 classic asp VBscript 转换为 C# .net 时遇到问题 我需要c# 的行为类似于VBScript 的结果

公式是这样的

Dim dTravelHours, result
dTravelHours = 22.7359890666919
result = (CDbl(dTravelHours)*2 + 2)\8

数学上的结果是 5.9331475 但是因为我使用整数除法而不是小数除法 "/" 结果是 5 ,我可以通过简单地将结果类型转换为 int 在 c# 中正确地得到这个结果

但是,如果我使用不同的值:

Dim dTravelHours, result
    dTravelHours = 22.7359890666919
    result = (CDbl(dTravelHours)*2 + 2.5)\8

数学结果是 5.9956475 vbScript 结果为 6

与 5.9456475 相同,vbscript 结果为 6

如何在 C# 中复制相同的行为? 我已经尝试过使用Math.Floor,Math.CeilingMath.Round,但还是不行。

提前感谢您的回答和建议

【问题讨论】:

  • Math.Ceiling(5.9956475) 是 6,这就是你想要的吧?
  • 是的,没错,但在 VBScript 中 5.9331475 是 5,因为它使用整数除法,但 5.9956475 是 6,如果我在 C# 中简单地使用 Ceiling,它的结果都是 6,这不是相同的结果与 VBScript 中的那个,
  • 所以 5.9331475 应该是 5 而 5.9456475 应该是 6?它的规则是什么?
  • 你想要 5 还是 6 ?这应该对您有所帮助:salman-w.blogspot.co.id/2009/10/…
  • 是的蒂姆,没错,5.9956475 也是 6,

标签: c# asp.net math


【解决方案1】:

正如 MSDN 所述,VbScript integer division operator 是以这种方式实现的:

结果是 number1 除以 number2 的整数商。这 整数商丢弃任何余数并仅保留整数 部分。在执行除法之前,对数值表达式进行四舍五入 到 Byte、Integer 或 Long 子类型表达式。

Round 是这样实现的:它默认返回整数,并将一半舍入为偶数或银行家的舍入(C# 中的默认值)。

因此,您可以使用 Math.Round 和整数除法来使用此 C# 版本:

double value = 22.7359890666919;
double calculationResult1 = value * 2 + 2.0;
double calculationResult2 = value * 2 + 2.5;
double rounded1 = Math.Round(calculationResult1);  // 47
double rounded2 = Math.Round(calculationResult2 ); // 48
int result1 = (int)rounded1 / 8;  // 5
int result2 = (int)rounded2 / 8;  // 6

【讨论】:

  • 哇,蒂姆!从来没想过,我只是在除以 8 之前将 Math.Round 中的公式分开,它起作用了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多