在C中创建round_up(float)函数时出错

Ton*_*yGW 1 c function rounding

我正在尝试编写一个将浮点数转换为整数的round_up函数,但是我的获取小数位数(浮点数%1的余数)似乎有误.如果浮点数是4.4,我希望将其转换为4; 如果它是4.5,我希望将其转换为5. 错误消息:错误:无效的操作数到二进制%(有'浮动'和'int')

int round_up(float x)
{
    int remainder;
    int ret_whole_num;

    ret_whole_num = x/1;
    remainder = x % 1.0;   /* this causes errors */

    if (remainder > 5) 
        return ret_whole_num += 1;

    return ret_whole_num;
}
Run Code Online (Sandbox Code Playgroud)

alk*_*alk 5

像这样做:

int round_zero_digits(float x)
{
  return x + 0.5;
}
Run Code Online (Sandbox Code Playgroud)

或者更一般:

#include <math.h> /* for pow()  */

...

float round_n_digits(float x, unsigned int n)
{
  x *= pow(10., n);

  x = (int) (x + 0.5);

  while (n--)
  {
    x /=10.;
  }

  return x;
}
Run Code Online (Sandbox Code Playgroud)

随着round_n_digits(x, 0)等同于round_zero_digits(x).

更新(不使用mathlib):

float round_n_digits(float x, unsigned int n)
{
  unsigned int n_save = n;

  while (n--)
  {
    x *= 10.;
  }

  x = (int) (x + 0.5);

  while (n_save--)
  {
    x /= 10.;
  }

  return x;
}
Run Code Online (Sandbox Code Playgroud)

更新^ 2(纯粹的C'ish方式):

#define ROUND_ZERO_DIGITS(x) ((int) ((x) + 0.5))

float round_n_digits(float x, unsigned int n)
{
  unsigned int n_save = n;

  while (n--)
  {
    x *= 10.;
  }

  x = ROUND_ZERO_DIGITS(x);

  while (n_save--)
  {
    x /= 10.;
  }

  return x;
}
Run Code Online (Sandbox Code Playgroud)

随着ROUND_ZERO_DIGITS()功能的宏观版本round_zero_digits().

  • @ThoAppelsin:好吗?你测试过这个吗? (2认同)