【问题标题】:Using round() function in c在c中使用round()函数
【发布时间】:2016-08-25 15:43:38
【问题描述】:

我对 C 中的 round() 函数有点困惑。

首先,男人说:

SYNOPSIS
   #include <math.h>
   double round(double x);

RETURN VALUE
   These functions return the rounded integer value.
   If x is integral, +0, -0, NaN, or infinite, x itself is returned.

返回值为double / floatint?

其次,我创建了一个函数,它先循环,然后转换为 int。稍后在我的代码中,我将其用作 比较双精度数

int tointn(double in,int n)
{
    int i = 0;
    i = (int)round(in*pow(10,n));
    return i;
}

这个函数显然在我的测试中不稳定。这里有冗余吗?嗯...我不只是在寻找答案,而是对这个主题有更好的理解。

【问题讨论】:

  • 返回值始终为doublefloat。如果您输入的数字类似于42.000,即使您传递了doublefloat,这也被认为是完整的。 “不稳定”是什么意思?如果您要比较 doubles,您还应该注意机器 epsilon 的浮点值。
  • 你可以从你发布的那个人的第一部分看到round()函数返回一个double
  • 当 n 很大时,您不能依赖 pow(10,n) 的精度。在您的测试中,n 的通常/最大值是多少?
  • 还是不清楚。如果42.000 存储为浮点数或双精度数,则其含义与将42.000 存储为int 完全不同。
  • 是的,它说的是“整数”而不是int。整数是整数,不是语言类型。

标签: c rounding


【解决方案1】:

手册页中的措辞应按字面意思阅读,即在数学意义上。 “x 是整数”表示xZ 的一个元素,而不是x 的数据类型为int

double 转换为 int 可能很危险,因为 double 可以容纳的最大任意整数值为 2^52(假设符合 IEEE 754 binary64 ),int 可以容纳的最大值可能更小(在 32 位架构上主要是 32 位,在某些 64 位架构上是 32 位)。

如果你只需要十次方,你可以自己用这个小程序测试它:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(){
  int i;
  for(i = 0;i < 26;i++){
    printf("%d:\t%.2f\t%d\n",i, pow(10,i), (int)pow(10,i));
  }
  exit(EXIT_SUCCESS);
}

您应该使用返回正确整数数据类型的函数,而不是强制转换,例如:lround(3)

【讨论】:

  • 谢谢,我不知道 lround()。我会试试的。
【解决方案2】:

这里是手册页的摘录。

   #include <math.h>

   double round(double x);
   float roundf(float x);
   long double roundl(long double x);

注意:返回值绝不是整数。但是,返回值的小数部分设置为 0。

注意:根据具体调用哪个函数来确定返回值的类型。

以下是手册页中关于舍入方式的摘录:

   These functions round x to the nearest integer, but round halfway cases
   away  from  zero  (regardless  of  the  current rounding direction, see
   fenv(3)), instead of to the nearest even integer like rint(3).

   For example, round(0.5) is 1.0, and round(-0.5) is -1.0.

【讨论】:

  • "但是,返回值的小数部分设置为 0。"准确度是多少?
  • 很高兴您提到了“中途案例”。例如,0.5 可以是 0.5000001 或 0.49999998 的事实又如何呢? 'round()' 是如何处理的?
  • @Mattana,强烈建议阅读round() 的手册页以获取所有详细信息/无论显示价值。这是round() 所做的事情之一。小于 0.5 的值将向 0 舍入,如 floor() 函数。大于 0.5 的值将向无穷大舍入,如 ceil() 函数。请务必注意总数为负数的情况下的细微差异
【解决方案3】:

如果要返回长整数,请使用lround:

long int tolongint(double in)
{
    return lround(in));
}

有关详细信息,请参阅从 C++ 11 标准开始提供的 lround

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多