在计算中当数字不以小数结束时返回0的困惑。

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

Confusion about returning 0 on calculation when the number doesn't end in a decimal

问题

问题是:

def BossArmor(armor)

	result = ((armor / (armor + 16635)) * 100)
	puts result

end

返回0,而

def BossArmor(armor)

	result = ((armor / (armor + 16635.0)) * 100)
	puts result

end

返回正确的值(59.54228178125835)

整个代码如果这样写:

def RegularArmor(armor)

	result = ((armor / (armor + 15232.5)) * 100)
	puts result

end

def BossArmor(armor)

	result = ((armor / (armor + 16635.0)) * 100)
	puts result

end

def GetArmorSafely
	puts "你有多少护甲?"
	armor = gets

	if armor =~ /^-?[0-9]+$/
		armor = armor.to_i
		RegularArmor(armor)
		BossArmor(armor)
	else
		puts "无效输入,只接受整数。"
		GetArmorSafely()
	end

end

GetArmorSafely()
英文:

I'm new to coding and I wrote something quickly to calculate armor against certain enemies based on level for WoTLK classic so I wouldn't have to keep going back to WolframAlpha.

Problem is

def BossArmor(armor)

	result = ((armor / (armor + 16635)) * 100)
	puts result

end

Returns 0, while

def BossArmor(armor)

	result = ((armor / (armor + 16635.0)) * 100)
	puts result

end

Returns the correct amount (59.54228178125835)

Entire code if that is important at all

def RegularArmor(armor)

	result = ((armor / (armor + 15232.5)) * 100)
	puts result

end

def BossArmor(armor)

	result = ((armor / (armor + 16635.0)) * 100)
	puts result

end

def GetArmorSafely
	puts "How much armor do you have?"
	armor = gets

	if armor =~ /^-?[0-9]+$/
		armor = armor.to_i
		RegularArmor(armor)
		BossArmor(armor)
	else
		puts "Invalid input, only integers are accepted."
		GetArmorSafely()
	end

end

GetArmorSafely()

I assume this has something to do with .0 making it a float/decimal or something similar, but I can't wrap my head around why it returns 0 without it. Maybe it has to do with me converting the input string to an integer?

To my knowledge I'm just throwing an integer into a simple calculation.

Any answers would be appreciated.

答案1

得分: 1

当两个整数相除时,结果为整数。例如:

irb(main):001:0> 1 / 2
=> 0

但如果其中一个是浮点数,则结果将为浮点数。

irb(main):002:0> 1 / 2.0
=> 0.5

整数可以使用#to_f方法转换为浮点数。

irb(main):005:0> 1.to_f / 2
=> 0.5

也可以使用#fdiv方法。

irb(main):007:0> 1.fdiv(2)
=> 0.5
英文:

When dividing two integers, the result is an integer. E.g.

irb(main):001:0> 1 / 2
=> 0

But if one of these is a floating point number, the result will be a floating point number.

irb(main):002:0> 1 / 2.0
=> 0.5

An Integer can be converted to a Float with the#to_f method.

irb(main):005:0> 1.to_f / 2
=> 0.5

It's also possible to use the #fdiv method.

irb(main):007:0> 1.fdiv(2)
=> 0.5

huangapple
  • 本文由 发表于 2023年4月17日 12:14:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031677.html
匿名

发表评论

匿名网友

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

确定