Printed double value differs from originally set value

后端 未结 3 440
慢半拍i
慢半拍i 2021-01-25 15:52

I am adding two array which contains double values

 let arrayA = [1.1,2.3]
 let arrayB = [4.2,5.5,6.8]

 let c = arrayA + arrayB

 print(\"\\(c)\");


        
相关标签:
3条回答
  • 2021-01-25 16:21

    You need to change as below :

    defind type of array because you have not defined at now .

     let arrayA : [CGFloat] = [1.1,2.3]
     let arrayB : [CGFloat] = [4.2,5.5,6.8]
    
    0 讨论(0)
  • 2021-01-25 16:25

    The reason for what you are seeing (1.1 -> 1.1000000000000001) lies in the nature of floating points. It is caused by rounding errors, as the infinite nature of real numbers can not be presented in its finite memory (floating point) representation.

    This might not be a big issue in your case, as you can change the printed format as stated in other answers, but can cause hard to track bugs, especially when comparing floating point numbers. For instance, the following code:

    let result = 1.1 * 3.0
    
    if result == 3.3 {
        print("I thought so!")
    } else {
        print("This might be unexpected")
    }
    

    prints:

    This might be unexpected
    

    For more information I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic:

    0 讨论(0)
  • 2021-01-25 16:36

    You don't. It's the way Double (and Float) does work.

    As workaround you can round your values when you are going to print them

    for num in c {
        print(String(format: "%.1f", num))
    }
    

    1.1

    2.3

    4.2

    5.5

    6.8

    0 讨论(0)
提交回复
热议问题