代码之家  ›  专栏  ›  技术社区  ›  litterbugkid

来自数据库的结果-无法将数组强制转换为浮点(TypeError)

  •  0
  • litterbugkid  · 技术社区  · 13 年前

    我从数据库中检索了一个Float值,并试图将其添加到Float类型的值中,结果出现错误: in '+': Array cant be coerced into Float (TypeError)

    total = 0.0
    db = SQLite3::Database.open "Checkout.sqlite"
    
    for i in 0..@items.length
        tempPrice = db.execute "SELECT price FROM Products WHERE product_code = ?", @items[i]
        total = total + tempPrice
    end
    
    2 回复  |  直到 13 年前
        1
  •  1
  •   Igor Kapkov    13 年前

    tempPrice 是数组,您应该使用 tempPrice[0] 如果您确定它只有1个值,或者您可以使用 tempPrice.sum if结果可以有多个值。

    更新日期: 尝试

    total = 0.0
    db = SQLite3::Database.open "Checkout.sqlite"
    
    @items.each do |item|
        db.execute("SELECT price FROM Products WHERE product_code = ?", item) do |row|
            total = total + row[0]
        end
    end
    
        2
  •  0
  •   saihgala    13 年前
    total = 0.0
    db = SQLite3::Database.open "Checkout.sqlite"
    
    for i in 0..@items.length
        db.execute("SELECT price FROM Products WHERE product_code = ?", @items[i]) do |row|
            total = total + row[0]
        end
    end
    
    推荐文章