Objective-C表达式-Objective-C 整型值和浮点值的相互转换

来源:互联网 发布:论文投稿中教数据 编辑:程序博客网 时间:2024/06/01 23:48
要想在以后更有效地开发Objective-C程序,就必须理解整型值浮点值之间进行隐式转换的规则。下面的范例4-5表明数值数据类型间的一些简单转换。

01 // Basic conversions in Objective-C
02 
03 #import <Foundation/Foundation.h>
04 
05 int main (int argc, const char * argv[])
06 {
07     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
08     float    f1 = 123.125, f2;
09     int        i1, i2 = -150;
10     
11     i1 = f1;                // floating to integer conversion
12     NSLog(@"%f assigned to an int produces %i", f1, i1);
13     
14     f1 = i2;                // integer to floating conversion
15     NSLog(@"%i assigned to a float produces %f", i2, f1);
16     
17     f1 = i2 / 100;            //integer divided by integer
18     NSLog(@"%i divided by 100 produces %f", i2, f1);
19     
20     f2 = i2 / 100.0;        //integer divided by a float
21     NSLog(@"%i divided by 100.0 produces %f", i2, f2);
22     
23     f2 = (float) i2 / 100;    //type cast operator
24     NSLog(@"(float) %i divided by 100 produces %f", i2, f2);
25     
26     [pool drain];
27     return 0;
28 }

最终输出结果:

123.125000 assigned to an int produces 123

-150 assigned to a float produces -150.000000

-150 divided by 100 produces -1.000000

-150 divided by 100.0 produces -1.500000

(float) -150 divided by 100 produces -1.500000


在Objective-C中,只要将浮点值赋值给整型变量,数字的小数部分都会被删节。因此在范例11行,把f1的值指派给i1时,只有整数部分被存储到i1中。

范例14行,把整型变量指派给浮点变量的操作不会引起数字值的任何改变。

范例17行,由于是两个整数的运算,按照整数运算规则,结果的任何小数部分都将删除。

范例20行,一个整数变量和一个浮点常量。在Objective-C中,任何处理两个值的运算如果其中一个值是浮点变量或常量,那么这个运算将做为浮点运算来处理。

最后一个除法运算,范例23行,我们看到如何在声明和定义方法时将类型放入圆括号中来声明返回值和参数的类型。为了求表达式值,类型转换运算符将变量i2的值转换成float类型。该运算符永远不会影响变量i2的值;它是一元运算符,行为和其他一元运算符一样。因此表达式-a永远不会影响a的值,表达式(float)a也不会影响a的值。

优先级上,类型转换运算符比所有算术运算符的优先级都高,但一元减号运算符除外。下面再举个类型转换运算符的例子:

(int) 29.55 + (int) 21.99

再Objective-C中等价于 29 + 21

类型转换运算符通常用于将一般id类型的对象转换成特定类的对象。例如:

id myNumber;
Fraction *myFraction;
  ...
myFraction = (Fraction *) myNumber;

将变量myNumber的值转换成一个Fraction对象。转换结果将指派给Fraction变量myFraction。

笔者Mike在CSDN上传了范例4-5链接,欢迎大家下载。Basic_Conversions