Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 除以两个变量返回0_Ruby - Fatal编程技术网

Ruby 除以两个变量返回0

Ruby 除以两个变量返回0,ruby,Ruby,当我将其设置为ratio=needed/count时,函数工作,但我需要一个百分比,因此当我将其设置为ratio=count/needed时,理论上应该返回一个小数点,但它返回0。我做错了什么?我需要它返回正确的数字来设置宽度百分比 def percent_bar(piece, options={}) count = file.total_count needed = HD::Application.config.files_needed ratio = count

当我将其设置为
ratio=needed/count
时,函数工作,但我需要一个百分比,因此当我将其设置为
ratio=count/needed
时,理论上应该返回一个小数点,但它返回0。我做错了什么?我需要它返回正确的数字来设置宽度百分比

  def percent_bar(piece, options={})
    count = file.total_count
    needed = HD::Application.config.files_needed
    ratio = count / needed
    percent = ratio * 100
    s = "<div class='progress'>"
    s += "<div class='progress-bar' role='progressbar' aria-valuemax='#{needed}' aria-valuenow='#{count}' aria-valuemin='0' style='width: #{ratio}%;'>"
    s += "<span class='sr-only'>#{count} of #{needed}</span>"
    s += "</div>"
    s += "</div>"

    return s

  end
def百分比_条(件,选项={})
计数=文件总数\u计数
需要=HD::Application.config.files\u需要
比率=计数/需要
百分比=比率*100
s=“”
s+=“”
s+=“{needed}中的{count}”
s+=“”
s+=“”
返回s
结束

您正在除以两个整数值,因此结果将始终为整数

改为这样做:

count / needed.to_f
例如:

count = 1
needed = 2
count / needed
# => 0
count / needed.to_f # type conversion to float
# => 0.5

这是因为正在执行整数除法。使用
转换为
float


ratio=count/needed。要了解变量类型及其对运算符的影响,请阅读。