Objective c 目标c浮点数转换
他们之间有什么不同Objective c 目标c浮点数转换,objective-c,floating-point,numbers,Objective C,Floating Point,Numbers,他们之间有什么不同 float f2,f1 = 123.125; 如果我把代码写成 float f1 = 123.125,f2; 该程序将产生不同的结果 这是完整的程序 float f1,f2 = 123.125 如果要初始化具有相同值的两个变量,请使用以下语法: float f2,f1 = 123.125; //float f1 = 123.125,f2; int i1,i2 = -150; i1 = f1; //floating to integ
float f2,f1 = 123.125;
如果我把代码写成
float f1 = 123.125,f2;
该程序将产生不同的结果
这是完整的程序
float f1,f2 = 123.125
如果要初始化具有相同值的两个变量,请使用以下语法:
float f2,f1 = 123.125;
//float f1 = 123.125,f2;
int i1,i2 = -150;
i1 = f1; //floating to integer
NSLog(@"%f assigned to an int produces %i",f1,i1);
f1 = i2; //integer to floating
NSLog(@"%i assigned to a float produces %f",i2,f1);
f1 = i2/100; //integer divided by integer
NSLog(@"%i divied by 100 prouces %f",i2,f1);
f2= i2/100.0; //integer divided by a float
NSLog(@"%i divied by 100.0 produces %f",i2,f2);
f2= (float)i2 /100; // type cast operator
NSLog(@"(float))%i divided by 100 produces %f",i2,f2);
您正在使用的代码是初始化其中一个变量,而不是另一个变量,因此您看到的行为是这样的。如果要初始化两个具有相同值的变量,请使用以下语法:
float f2,f1 = 123.125;
//float f1 = 123.125,f2;
int i1,i2 = -150;
i1 = f1; //floating to integer
NSLog(@"%f assigned to an int produces %i",f1,i1);
f1 = i2; //integer to floating
NSLog(@"%i assigned to a float produces %f",i2,f1);
f1 = i2/100; //integer divided by integer
NSLog(@"%i divied by 100 prouces %f",i2,f1);
f2= i2/100.0; //integer divided by a float
NSLog(@"%i divied by 100.0 produces %f",i2,f2);
f2= (float)i2 /100; // type cast operator
NSLog(@"(float))%i divided by 100 produces %f",i2,f2);
float f2 = f1 = 123.125f;
您正在使用的代码是初始化其中一个变量,而不是初始化另一个变量,因此您看到的行为
float f2 = f1 = 123.125f;
如果要初始化这两个变量,需要执行以下操作
float f2,f1 = 123.125; // here you leave f2 uninitialized and f1 is initialized
float f1 = 123.125,f2; // here you leave f2 uninitialized and f1 is initialized
float f1,f2 = 123.125; // here you leave f1 uninitialized and f2 is initialized
最好是这样写(为了可读性)
注意“f”后缀,它表示它是一个浮点值而不是双精度值
您还可以进行定义
float f1 = 123.125f;
float f2 = 123.125f;
如果要初始化这两个变量,需要执行以下操作
float f2,f1 = 123.125; // here you leave f2 uninitialized and f1 is initialized
float f1 = 123.125,f2; // here you leave f2 uninitialized and f1 is initialized
float f1,f2 = 123.125; // here you leave f1 uninitialized and f2 is initialized
最好是这样写(为了可读性)
注意“f”后缀,它表示它是一个浮点值而不是双精度值
您还可以进行定义
float f1 = 123.125f;
float f2 = 123.125f;
那么NSLogs的输出是什么呢?那么NSLogs的输出是什么呢?嗨,谢谢你的回答,我试图更改你刚才提供的代码,整个程序根本无法运行。嗨,谢谢你的回答,我试图更改你刚才提供的代码,整个程序根本无法运行。
f
后缀在此上下文中是可选的,因为编译器将适当地更改文本的类型。:)编译器将文本的类型转换为声明对象的类型并不是使其在此上下文中成为可选的事实。相反,这是一个事实,转换不会改变这个文本。大多数双字面值在转换时都会更改值,少数会更改为不同于带有“f”后缀的同一字面值的值。f
后缀在此上下文中是可选的,因为编译器将适当更改该字面值的类型。:)编译器将文本的类型转换为声明对象的类型并不是使其在此上下文中成为可选的事实。相反,这是一个事实,转换不会改变这个文本。大多数双字面值在转换时都会更改值,少数会更改为与后缀为“f”的同一字面值不同的值。