math.Mod在Go语言中返回整数部分而不是浮点数的余数。

huangapple go评论89阅读模式
英文:

math.Mod in Go returns integer part instead of floating-point remainder

问题

Golang的**math.Mod(10, 4)**返回2 - 即除法结果2.5的整数部分 - 但它不应该是“浮点数的余数”,也就是0.5吗?

英文:

Golang's math.Mod(10, 4) returns 2 -- ie. the integer part of division result 2.5 -- but shouldn't it be "the floating point remainder", that is, 0.5?

答案1

得分: 22

结果是正确的。math.Mod返回的是余数,在这个例子中实际上是2。它相当于%运算符,但适用于浮点数。

英文:

The result is correct. math.Mod returns the remainder, which really is 2 in this case. It's equivalent to the % operator, but for floating point numbers.

答案2

得分: -1

如果你想要在浮点数除法后获得小数部分的值,我理解你想要的是这样的代码:

double A = 10.0;
double B = 4.0;
double divResult = A / B;
double fractional = divResult % 1.0;
//打印结果为 "10.0 / 4.0 小数部分余数: 0.5"
System.out.printf("%f / %f 小数部分余数: %f", A , B, fractional);
英文:

if you're looking for the value after the decimal place after doing floating point division, as I understand, you would want something like this:

double A = 10.0;
double B = 4.0;
double divResult = A / B;
double fractional = divResult % 1.0;
//prints "10.0 / 4.0 fractional remainder: 0.5"
System.out.printf("%f / %f fractional remainder: %f", A , B, fractional);

huangapple
  • 本文由 发表于 2012年5月18日 17:32:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/10650095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定