【问题标题】:objective c float numer conversion目标c浮点数转换
【发布时间】:2012-07-20 07:06:30
【问题描述】:
  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); 

【问题讨论】:

  • 那么 NSLogs 的输出是什么......??

标签: objective-c floating-point numbers


【解决方案1】:
  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;

【讨论】:

  • f 后缀在这种情况下是可选的,因为编译器会适当地更改文字的类型。 :)
  • 并不是编译器将文字的类型转换为声明对象的类型,这使得它在此上下文中是可选的。相反,这个字面量不会因转换而改变。大多数双精度字面值在转换时确实会改变值,并且少数会更改为与带有“f”后缀的相同字面量不同的值。
【解决方案2】:

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

float f2 = f1 = 123.125f;

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

【讨论】:

  • 您好,谢谢您的回答,我尝试更改您刚刚提供的代码,整个程序根本无法运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多