具有十进制增量的循环的Javascript具有错误的输出

时间:2017-03-22 07:55:27

标签: javascript loops for-loop

我有一个问题,我认为这是一个错误。所以我创建了一个for循环:

class Class
  def attr_accessor_with_history(attr_name)
    attr_setter_name = :"#{attr_name}="
    attr_getter_name = :"#{attr_name}"
    attr_hist_name = :"@#{attr_name}_history"
    attr_name = :"@#{attr_name}"

    self.class_eval do
      define_method(attr_getter_name) do
        instance_variable_get(attr_name)
      end

      define_method(attr_setter_name) do |val|
        instance_variable_set(attr_name, val)
        history = instance_variable_get(attr_hist_name)
        instance_variable_set(attr_hist_name, history = []) unless history
        history << val
      end
    end
  end
end

class Object
  def history(attr_name)
    attr_hist_name = :"@#{attr_name}_history"
    instance_variable_get(attr_hist_name)
  end
end

输出对于所有值范围都是正确的,除了长度= 10.8或其任何倍数的实例。输出显示为multi = 12,实际上它应该是11。

有人能告诉我为什么会这样吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

var multi=2;
 for (limit=0; limit < 10.8; limit += 1.2) {
      multi++;console.log(limit +"-"+multi);
 }
 console.log(multi);

输出

  

0-3

     

1.2-4

     

2.4-5

     

3.5999999999999996-6

     

4.8-7

     

6-8

     

7.2-9

     

8.4-10

     

9.6-11

     

10.799999999999999-12 //是的,应该是10.8

所以最终的多数将是12。 10.79小于10.8因此多将增加

答案 1 :(得分:0)

因为多值是2

var length = 10.8
var multi  = 1;
 for(limit = 0; limit<length; limit+=1.2) {
      multi++;
 }

console.log(multi); // 11

您可以更改限制+ = 1.2以限制+ = 1.3以获得11

var length = 10.8
var multi  = 2;
 for(limit = 0; limit<length; limit+=1.3) {
      multi++;
 }

console.log(multi); // 11