二元运算符/不能应用于 Int 和 Double 类型的操作数 [英] binary operator / cannot be applied to operands of type Int and Double

查看:49
本文介绍了二元运算符/不能应用于 Int 和 Double 类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,Swift 的新手,以及一般的编程.通过练习给出的代码正是:

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

但我收到错误消息,二元运算符/不能应用于 Int 和 Double 类型的操作数".

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

经过一番挖掘后,我发现您不能同时对 Integer 和 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.

使用 El Capitan 测试版和 Xcode 7 测试版.

Using El Capitan beta and Xcode 7 beta.

推荐答案

高度和宽度都将被推断为 Int 类型.因此 area 也是 Int 类型,而 10.762 是 Double 类型.

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

在 Swift 中安全是最重要的,所以你需要有两个相同类型的操作数.

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

解决方案是(如 Eric D. 建议的)将区域转换为双精度:

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

let areaInMeters = Double(area) / 10.762

这篇关于二元运算符/不能应用于 Int 和 Double 类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆