binary operator / cannot be applied to operands of type Int and Double [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-30 10:04:32

问题


Hello brand new to Swift, and programming in general. Going through an exercise the code given is exactly:

//: Playground - noun: a place where people can play

import UIKit

let height = 12
let width = 10


let area = height * width

let areaInMeters = area / 10.762

But I get the error, "binary operator / cannot be applied to operands of type Int and Double".

After some digging around I found you can't operate on both an Integer and a Double. So I changed the last line to:

let areaInMeters = (Double)area / 10.762

Then I get the error, "Consecutive statements on a line must be separated by a ;" and it wants me to put the ; after area. None of this is making any sense to me.

Using El Capitan beta and Xcode 7 beta.


回答1:


height and width will both be inferred as of type Int. Therefore area is also of type Int whilst 10.762 is a Double.

And in Swift safety is paramount so you'll need to have both operands of same type.

Solution is (as Eric D. suggested) is to convert area to a Double:

let areaInMeters = Double(area) / 10.762



回答2:


Try instead adding a decimal point and a zero to the end of your height and width.

Like so:

let height = 12.0 let width = 10.0

And you won't have to worry about having to deal with an Integer. Hope this helps. Happy Coding!



来源:https://stackoverflow.com/questions/30869313/binary-operator-cannot-be-applied-to-operands-of-type-int-and-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!