Swift 运算符

Swift 运算符报错

Swift 运算符报错

var radius = 4 
let pi = 3.14159
var area = radius * radius * pi

In case you’ve forgotten from math class, this computes the area of a circle. ;]
You might be surprised to see the compiler complain about the second multiplication operation with the error, cannot invoke ‘*’ with an argument list of type ‘($T4, Double).
What exactly does this mean?

All operations are defined as functions, and the above indicates that the compiler cannot find a multiplication function that takes an Int on the left hand side and a Double on the right.

以防你忘记数学公式,这个是等式用来计算圆的面积。
你可能会惊讶编译器对第二个乘法操作报错,当参数类型是“Double”时不能调用“*”,这究竟是怎么回事?

(在Swift中)所有的运算符都被定义为函数,以上的例子表明编译器找不到一个函数,这个函数的左边的参数是Int类型右边是Double类型

This illustrates a very important feature of the Swift language: all numeric type conversions must be explicit regardless of whether you want to convert to a type with more or less precision. This is true of integers as well as floating point numbers.
To fix the problem, update the code as follows:

var area = Double(radius) * Double(radius) * pi

这个例子是Swift语言非常重要的特性:所有的数字类型之间的转换必须是明确,清晰的,无论你是想提升或者降低精确度。这也适用于整数和浮点数。为了解决这个问题,按照以下的形式修改代码:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值