Ruby Float rationalize()方法及示例

Ruby Float rationalize()方法及示例

float rationalize()是一个float类的方法,它返回一个浮点数的简单有理形式(p/q)。

语法: float.reasonize()

参数: 作为参数的浮点数值

返回: 简单的近似值

例子 #1 :

# Ruby program for rationalize() method
  
# Initialize value
a = 0.767
b = 2999.011
  
# Printing result
puts "Rationalizing a : #{a.rationalize}\n\n"
puts "Rationalizing b : #{b.rationalize}\n\n"

输出:

Rationalizing a : 767/1000

Rationalizing b : 2999011/1000

例子#2

# Ruby code for rationalize() method
  
# Initialize value
a = 0.767
b = 2999.011
c = 2.0000
  
# Printing result
puts "Rationalizing a : #{a.rationalize(0.01)}\n\n"
puts "Rationalizing b : #{b.rationalize(0.00001)}\n\n"
puts "Rationalizing c : #{c.rationalize(0.1)}\n\n"

输出:

Rationalizing a : 10/13

Rationalizing b : 1634461/545

Rationalizing c : 2/1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程