【问题标题】:Objective-C Float RoundingObjective-C 浮点舍入
【发布时间】:2011-06-09 19:11:29
【问题描述】:

如何在 Objective-C 中将浮点数舍入到最接近的整数:

例子:

float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);

应该打印“四舍五入的浮点数是 46”

【问题讨论】:

    标签: iphone objective-c ios floating-point rounding


    【解决方案1】:

    使用 C 标准函数系列 round()roundf() 用于floatround() 用于doubleroundl() 用于long double。然后,您可以将结果转换为您选择的整数类型。

    【讨论】:

    • 我认为这是更好、更有效的方法。
    • 与 + 0.5 方法不同,它可以正确处理负数。
    • 嘿@JonathanGrynspan 很多答案都在这里链接到你的答案 - 用一些如何(以及为什么)使用每个答案的例子来扩展它会很棒。
    【解决方案2】:

    推荐的方式在这个答案中:https://stackoverflow.com/a/4702539/308315


    原答案:

    添加 0.5 后将其转换为 int。

    所以

    NSLog (@"the rounded float is %i", (int) (f + 0.5));
    

    编辑:您要求的方式:

    int rounded = (f + 0.5);
    
    
    NSLog (@"the rounded float is %i", rounded);
    

    【讨论】:

    • 这只会产生 向下 舍入。要获得 = .5 向上舍入: [NSString stringWithFormat:@"%i", (int)round(f)]
    • 其实没有。这将产生最接近的舍入。
    • 这不能正确处理负数。
    • 示例:-2.8 四舍五入应该是 -3,但是根据您的公式,我们有 -2.8 + 0.5 = -2.2,转换为 int 是 -2
    • @HaryantoCiu 什么是“最近舍入”
    【解决方案3】:

    float 舍入到最接近的整数使用roundf()

    roundf(3.2) // 3
    roundf(3.6) // 4
    

    您还可以使用ceil() 函数始终从float 获取上限值。

    ceil(3.2) // 4
    ceil(3.6) // 4
    

    对于最低值floor()

    floorf(3.2) //3
    floorf(3.6) //3
    

    【讨论】:

      【解决方案4】:

      在objective-c中对浮点数进行四舍五入的最简单方法是lroundf

      float yourFloat = 3.14;
      int roundedFloat = lroundf(yourFloat); 
      NSLog(@"%d",roundedFloat);
      

      【讨论】:

      • 不,最简单的方法是加 0.5 并截断。您不必记住“lroundf”即可执行此操作,而且您确切知道自己得到了什么。
      • @Hot Licks - 当然,除非您需要对正数和负数进行舍入(我的情况),而 0.5 方法存在缺陷。
      【解决方案5】:

      查看rint()的手册页

      【讨论】:

        【解决方案6】:

        如果你想在下面的整数中舍入浮点值是在目标 C 中舍入浮点值的简单方法。

        int roundedValue = roundf(Your float value);
        

        【讨论】:

          【解决方案7】:

          让我们尝试并结帐

          //Your Number to Round (can be predefined or whatever you need it to be)
          float numberToRound = 1.12345;
          float min = ([ [[NSString alloc]initWithFormat:@"%.0f",numberToRound] floatValue]);
          float max = min + 1;
          float maxdif = max - numberToRound;
          if (maxdif > .5) {
              numberToRound = min;
          }else{
              numberToRound = max;
          }
          //numberToRound will now equal it's closest whole number (in this case, it's 1)
          

          【讨论】:

          • 根据所提出的问题,我认为这个答案比上述任何一个都更有帮助..
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-11
          • 1970-01-01
          相关资源
          最近更新 更多