在不带“-”运算符的Golang中计算两个数字之间的差

问题描述 投票:0回答:2

我想在Golang中找到两个数字之间的差,结果不应该在“-”中。

请在下面找到我的代码:

    dollarValue := 240000 - 480000  

结果为“ -240000”。但是我的预期输出仅为“ 240000”。任何人都可以帮助您如何计算这两个数字之间的差。

go difference
2个回答
1
投票

您的标题具有误导性。应该是没有negative而不是- operator的状态。

基本上,您想要得到的是两个数字之间的绝对不同

您有两个选择:

  • 如果结果为负,则使用if / else条件返回正结果
  • 使用math.abs(需要从/转换为浮点数)

1
投票

只需实现您自己的方法

math.abs

并像这样使用它:

func diff(a, b int) int {
   if a < b {
      return b - a
   }
   return a - b
}
© www.soinside.com 2019 - 2024. All rights reserved.