计算器Ruby中的无限循环

时间:2014-12-15 17:38:59

标签: ruby loops do-while

我已经写了这段代码作为一个小计算器,因为我很无聊,但因为它似乎陷入无限循环,所以困扰我。我已经添加了一些注释来描述每个位的意图。

print "Enter your current humanity: "
current = gets.chomp("Enter Current Humanity: ") #Has user input current humanity
print "Enter the value of an AI bandit kill: "
bandit = gets.chomp ("What is the value of an AI bandit?") #Has user specify bandit's worth
kills = 0 #sets the needed kills to 0, to allow proper counting
hero = 5000

if Integer(current) >= Integer(hero)
  puts "You're already a hero"
elsif Integer(current) < Integer(hero)
  while Integer(current) < Integer(hero) do #SHOULD continue going until current is over 5000
    Integer(current) + Integer(bandit) #ERROR: "possibly useless use of + void context" What?
    Integer(kills) + 1
  end
else #everything under here probably will be removed anyhow
  puts "Something went wrong"
  puts "perhaps you've placed a non-integer in the inputs?"
end  
编辑:在阅读并回答答案之后,我发现循环是由于我对Ruby缺乏理解导致变量未被修改,以及我缺乏使用.to_i

我感谢大家的帮助。

3 个答案:

答案 0 :(得分:1)

嗯,问题在于将变量强制转换为整数。这里有很多不必要的代码,你正在进行的转换不会改变原始变量。

hero = 10
Integer(hero) + 1
# => 11
puts hero
# => 10 # notice hero is still 10, and not 11

相反,您可以在使用gets:

时转换为int
bandit.to_i

然后你的代码看起来像这样:

if current >= hero
  puts "You're already a hero"
elsif current < hero
  while current < hero
    current += bandit # not sure what you want to do here, frankly
    kills += 1
  end
else
  puts "Something went wrong"
  puts "perhaps you've placed a non-integer in the inputs?"
end 

无限循环不再是问题,因为你正在改变current。警告possibly useless use of +会因同样的原因而消失。

答案 1 :(得分:0)

它是一个无限循环,因为你永远不会改变你的任何变量。

print "Enter your current humanity: "
current = gets.chomp("Enter Current Humanity: ").to_i
print "Enter the value of an AI bandit kill: "
bandit = gets.chomp("What is the value of an AI bandit?").to_i
kills = 0
hero = 5000

if current >= hero
  puts "You're already a hero"
else
  while current < hero
    current += bandit
    kills += 1
  end
end

这段代码可能更接近你想要的,虽然我不能说我完全理解这一点,并且追踪杀戮并没有真正做任何事情,因为它从未使用过。

答案 2 :(得分:0)

您在任何地方都使用了对Integer转换的调用,只有在需要的地方才能解决问题:

print "Enter your current humanity: "
current = gets.chomp("Enter Current Humanity: ").to_i
print "Enter the value of an AI bandit kill: "
bandit = gets.chomp("What is the value of an AI bandit?").to_i
kills = 0
hero = 5000

if current >= hero
  puts "You're already a hero"
elsif current < hero
  while current < hero do
    current + bandit
    kills
  end
else
  puts "Something went wrong"
  puts "perhaps you've placed a non-integer in the inputs?"
end

正如您所看到的,您在while循环中正在执行current + bandit,但实际上并未对其结果进行任何操作,并且不会因此而更改变量。

您想要在该行上做的是:

current += bandit
kills += 1

其中current的值增加bandit

请注意,我已使用to_i将字符串转换为int,因为这可以防止用户输入空字符串时出错。