需要使用小型计算器的一些指导,我正在研究Ruby

zappdapper
def averager
puts "Put in three numbers. One per line"
num_1 = $stdin.gets.chomp.to_i
num_2 = $stdin.gets.chomp.to_i
num_3 = $stdin.gets.chomp.to_i

half_total =  num_1 + num_2 + num_3
total = half_total / 3
end

好的,这是我正在研究的一个平均水平。除了一件事,它工作正常。我希望用户决定他要输入多少个数字。这样,我将不会只限于平均三个数字。谢谢

阿古什

在这里,用#标记的注释逐行解释。

def averager
  puts "How many numbers?" #ask the user how many numbers
  numbers = gets.chomp.to_i #get how many numbers
  count = 1 #start the count variable for the while loop
  half_total = 0 #half_total starts on zero
  while(count <= numbers) do #while count is less than or equal to amount of numbers
    puts "Enter #{count}° number" #puts "Enter 1°,2° or whatever number"
    number = gets.chomp.to_i #get the actual number from the user
    half_total = half_total + number #add it to your half total
    count = count + 1 #add one to count so we go to the 2°,3° or wtv number
  end #end the loop

  total = half_total/numbers.to_f #divide half_total by the amount of numbers 
             #.to_f is used to force float division so decimals don't get cut

  puts "The average is: #{total}" #prints the result
  total #returns the result in case you don't want to print it

end #end of the function or method

这是通过简单的while循环完成的,就像其他答案所说的那样,如果您仍然对循环的工作方式感到困惑,请查看有关循环的教程http://www.tutorialspoint.com/ruby/ruby_loops.htm

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

做一个简单的计算器,但我需要添加一些东西

我需要一些关于 RegEx 模式的指导

用python编写计算器,需要一些帮助

需要一些 CSS 指导

作为初学者的移动开发人员,我需要一些指导

python3,尝试从我定义的函数中获取输出,需要一些指导

我需要一些关于 Web API 的指导 - MVC 应用程序

我正在尝试使用AddEventListener和QuerySelector创建一个简单的Javascript计算器

我做了一个年龄计算器,我需要刷新以重新使用

需要一些指导来使用淘汰赛js实现任务

Qt和RTI DDS交互---需要一些指导

我需要使用perl从字符串中提取一些位于方括号之间的值

我想制作一个平均值计算器,但我遇到了一些问题

我想要创建一些目录的指导

我一直在这里研究基于 python 公式的基本计算器

我是 C# 新手,我正在尝试研究一些排序算法 如何让我的选择排序接受负数?

我需要有关Docker返回非零代码100的一些指导

需要使用 ansible 运行一些数据库脚本。但是db脚本在执行时正在调用其他脚本

为什么在我要使用的每个文件中都需要导入一些Pod,而只需要导入一次?

我目前正在用 pygame 制作游戏,我需要一些矢量代码的解释

需要使用XSLT删除Json输出中的一些元素

需要使用 R 脚本从列中删除一些特定的字符串

如何从需要使用Ansbile进行身份验证的网站上获取一些数据?

需要使用CS50滤镜灰度的一些初始方向

我正在尝试制作一个计算器,一个简单的

我正在尝试实现此接口,但需要一些帮助:

我正在尝试构建一个简单的计算器

我正在尝试创建一个蒸汽税计算器,但它失败得可怕

我正在尝试在Ruby上执行股票选择器方法,但是我的代码中存在一些问题