英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论