本文介绍了CGFloat添加错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在程序中递归添加一些CGFloat值。我刚刚在一个特定情况下意识到生成的总数是不正确的。为了确保我的程序逻辑没有任何问题,我创建了一个该场景的简单示例(见下文),并打印出相同的错误值。

I was trying to add some CGFloat values recursively in my program. And I just realized in one particular scenario the total generated was incorrect. To ensure I had nothing wrong in my program logic, I created a simple example of that scenario (see below) and this printed the same wrong value.

CGFloat arr[3] = {34484000,512085280,143011440};
CGFloat sum = 0.0;
sum = arr[0] + arr[1] + arr[2];

NSLog(@"%f",sum);

int arr1[3] = {34484000,512085280,143011440};
int sum1 = 0.0;
sum1 =  arr1[0] + arr1[1] + arr1[2];

NSLog(@"%d",sum1);

第一个NSLog打印689580736.000000 ...而正确的结果是689580720.但是第二个NSLog打印正确结果。我不确定这是一个错误还是我做错了。

The first NSLog prints 689580736.000000...while the correct result 689580720. However the second NSLog prints the correct result. I am not sure if this is a bug or if I am doing something wrong.

谢谢,
Murali

Thanks,Murali

推荐答案

CGFloat 是32位目标(如iOS)上的单精度浮点数 - 它只有23位尾数,即大约6 - 7位数。如果您需要更高的准确度,请使用双精度类型。

CGFloat is a single precision float on 32 bit targets such as iOS - it only has a 23 bit mantissa, i.e. around 6 - 7 significant digits. Use a double precision type if you need greater accuracy.

您应该阅读David Goldberg的,然后再继续学习编程。

You should probably read David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic before proceeding much further with learning to program.

这篇关于CGFloat添加错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:17