在为CGFloat赋值时使用'f'的意义是什么? [英] What is the point of using 'f' when assigning a value to a CGFloat?

查看:404
本文介绍了在为CGFloat赋值时使用'f'的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直看到这个:

  CGFloat someCGFloat = 1.2f; 

为什么使用'f'?如果 CGFloat 定义为 float ,则该值将转换为 float ,如果 CGFloat 被定义为 double ,那么该值将被转换为 double



这只是为了确保从 double float 不会发生?有什么要点?

编辑: Hmmm ...哪个答案接受...两个都很好!

p>

解决方案

1.0默认是double,如果正确的值是1.2,则有一个隐式转换, (转换不是运行时操作)。在这种情况下,它不重要,称它为1.2f。程序员大多滥用它,但有些情况下它是非常重要的。



例如:

  float var = 1.0e-45; 
NSLog(@%d,var == 1.0e-45);

这打印零,因为1.0e-45太小,无法存储到单精度浮点变量,因此它变为等于零。编写var == 1.0e-45f会更改结果。



使用格式说明符在编写表达式时很重要,因为左边的值是一个浮点数,表达式被视为浮动,但这不是发生了什么。



更引人注目的情况是,当对一个数字使用l格式说明符时,这个数字变化为零,并对结果感到惊讶:

  long var = 1<< 32; //我假设一个int需要4个字节和一个长8个字节

结果为零,写入1l << 32完全改变结果。


I see this all the time:

CGFloat someCGFloat = 1.2f;

Why is the 'f' used? If the CGFloat is defined as float, the value will be converted to a float, and if the CGFloat is defined as a double, the value will be converted to a double.

Is it just to make sure a conversion from double to float doesn't occur? What's the point of doing that? Also, wouldn't the compiler take care of this?

EDIT: Hmmm…which answer to accept…both are very good!

解决方案

1.0 by default is double, if the right value is 1.2 there is an implicit cast, and the value gets casted from double to float (the cast isn't a runtime operation). In this case it's not important to call it 1.2f. Programmers mostly abuse it, but there are cases where it's really important.

For example:

float var= 1.0e-45;
NSLog(@"%d",var==1.0e-45);

This prints zero, because 1.0e-45 is too small to be stored into a single precision floating point variable, so it becomes equal to zero. Writing var==1.0e-45f changes the result.

Using format specifiers is important mostly when writing expressions, and since the left value is a float you expect that also the expression gets treated as a float, but that's not what happens.

A more striking case is when using the l format specifier on a number that gets shifted so much to become zero, and get surprised about the result:

long var= 1<<32;  // I assume that an int takes 4 bytes and a long 8 bytes

The result is zero, and writing 1l<<32 completely changes the result.

这篇关于在为CGFloat赋值时使用'f'的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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