如何在 Swift 中进行 int 和 float 之间的算术运算? [英] How to do arithmetic between int and float in Swift?

查看:35
本文介绍了如何在 Swift 中进行 int 和 float 之间的算术运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 Swift 编程的第一天,直到现在我们都在使用 Objective C.我尝试编写简单的加法程序,它可以工作.喜欢,

var i = 10无功j = 10var k = i + j打印(k)

但是当我将其中一个值更改为浮动时,它会出错.

var i = 10无功j = 10.4var k = i + j打印(k)

<块引用>

错误:main.swift:13:11:找不到+"的重载接受提供的参数

现在我做了谷歌搜索并尝试了一些东西,例如Double(i+j) ,但它不起作用.在这种情况下,Swift 应该隐式地将 int 转换为 float,不是吗?

如果我在理解 Swift 语言时犯了任何错误,请提出建议.

解决方案

根据您想要的结果,您应该使用该类型的 init 方法将其转换为适当的类型.

例如

var myInt = 5;var myDouble = 3.4;

如果我想要一个双倍的结果

var doubleResult = Double(myInt) + myDouble;

如果我想要一个整数,请注意双精度将被截断.

var intResult = myInt + Int(myDouble)

我在您的示例中看到的问题是您正在尝试执行加法操作,然后对其进行转换,但在执行加法之前,两个值必须相同.

为了避免类型不匹配和转换错误,Apple 已经非常严格.有时这对于来自其他语言的开发人员来说可能有点过于严格",起初我很生气,但我已经习惯了.

This is my first day in Swift programming and till now we are using Objective C. I tried to write simple addition program it works. Like,

var i = 10
var j = 10
var k = i + j
println(k)

But when I change one of the values to float it gives error.

var i = 10
var j = 10.4
var k = i + j
println(k)

Error: main.swift:13:11: Could not find an overload for '+' that accepts the supplied arguments

Now I did Google search and tried few thing e.g. Double(i+j) , but it doesn't work. Swift should implicitly convert int to float in this case, isn't it?

Please suggest if I am doing any mistake understanding Swift language.

解决方案

Depending on what you want your result to be, you should convert it to the appropriate type using that types init method.

eg.

var myInt = 5;
var myDouble = 3.4;

If I want a double for example in my result

var doubleResult = Double(myInt) + myDouble;

if I want an integer instead, please note the double will be truncated.

var intResult = myInt + Int(myDouble)

The problem I see in your example is you're trying to do an add operation and then convert it but both values needs to be the same before you perform the addition.

Apple has made it quiet strict to avoid type mis-match and conversion errors. Sometimes this can be a bit 'too strict' for dev coming from other languages, I was annoyed at first but I got used to it.

这篇关于如何在 Swift 中进行 int 和 float 之间的算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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