目标浮点数转换

问题描述 投票:1回答:2
  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); 
objective-c floating-point numbers
2个回答
4
投票
  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

如果要初始化两个变量,则需要做

  float f1 = 123.125f, f2 = 123.125f;  

最好您这样写(以提高可读性)

  float f1 = 123.125f;
  float f2 = 123.125f;  

请注意后缀“ f”,它表示它是浮点值而不是双精度值。

您也可以进行定义

#define INITVALUE 123.125f

float f1 = INITVALUE;
float f2 = INITVALUE;

0
投票

如果要初始化两个具有相同值的变量,请使用以下语法:

float f2 = f1 = 123.125f;

您正在使用的代码正在初始化一个变量,而不是另一个变量,因此您正在看到行为。

© www.soinside.com 2019 - 2024. All rights reserved.