Math divison in Swift

让人想犯罪 __ 提交于 2019-11-26 09:14:39

问题


I\'m trying to make a math app with different equations and formulas but I\'m trying to circle sector but i just wanted to try to divide the input value by 360 but when I do that it only says 0 unless the value is over 360. I have tried using String, Double and Float with no luck I don\'t know what I\'m doing is wrong but down here is the code. I\'m thankful for help but I have been sitting a while and searched online for an answer with no result I might have been searching with the wrong search.

if graderna.text == \"\"{
        }
        else{
            var myInt: Int? = Int(graderna.text!)    // conversion of string to Int
            var myInt2: Int? = Int(radien.text!)
            let pi = 3.1415926
            let lutning = 360


            let result = (Double(myInt! / lutning) * Double(pi))
            svar2.text = \"\\(result)\"
        }

回答1:


Your code is performing integer division, taking the integer result and converting it to a double. Instead, you want to convert these individual integers to doubles and then do the division. E.g.

let result = Double(myInt!) / Double(lutning) * pi

Or define

let lutning = 360.0

and then

let result = Double(myInt!) / lutning * pi

And, BTW, I'd suggest using M_PI rather than defining your own pi.

let result = Double(myInt!) / lutning * M_PI



回答2:


You are dividing an Int by an Int.

Integer division rounds to the nearest integer towards zero. Therefore for example 359 / 360 is not a number close to 1, it is 0. 360 / 360 up to 719 / 360 equals 1. 720 / 360 to 1079 / 360 equals 2, and so on.

But your use of optionals is atrocious. I'd write

let myInt = Int(graderna.text!)
let myInt2 = Int(radien.text!)

if let realInt = myInt, realInt2 = myInt2 {
    let pi = 3.1415926
    let lutning = 360.0

    let result = Double (realInt) * (pi / lutning)
    svar2.text = "\(result)"
}



回答3:


In the line let result = (Double(myInt! / lutning) * Double(pi)) you cast your type to double after dividing two integers so your result will always be zero. You have to make them doubles before division.

let result = (Double(myInt!) / Double(lutning)) * Double(pi))



来源:https://stackoverflow.com/questions/35383062/math-divison-in-swift

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