四舍五入到最近的数字红宝石

时间:2014-09-02 20:26:44

标签: ruby rounding

def percent_more
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"  

现在代码会告诉你max_number的最大值是minimum_number的百分比。但问题是它打印出一长串小数,这很难排序。所以,如果我希望代码只显示前三个数字,我会做什么?

3 个答案:

答案 0 :(得分:3)

您要使用的是total_percent_more.round,如下所示:

puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"                                                                        
smallest_number = gets.chomp                                                                               
difference = biggest_number.to_i - smallest_number.to_i                                                    
total_percent_more = difference / smallest_number.to_f                                                     
puts "Your biggest number is #{total_percent_more.round}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"

有关详细信息,请参阅文档:

http://www.ruby-doc.org/core-2.1.2/Float.html#method-i-round

在早于1.9的ruby版本中,你需要像这样使用sprintf:

puts "Your biggest number is #{sprintf('%.2f', total_percent_more)}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"

您可以通过更改数字来更改小数位数。

有关详细信息,请参阅文档:

http://www.ruby-doc.org/core-1.8.7/Kernel.html#method-i-sprintf

答案 1 :(得分:1)

result = 10/6.0
puts result
printf("%.3f\n", result)

--output:--
1.66666666666667
1.667

答案 2 :(得分:0)

以下是如何舍入到2位小数

的示例
amount = 342
puts amount.round(2)

如果你想要舍入到最接近的3位小数,那么就像:

puts amount.round(3)