Question

I am trying to write a round_up function that converts a float number to integer, but there seems to be error with my way of getting the decimal digits (the remainder of float number % 1). If the float number is 4.4, I wish to convert it to 4; if it's 4.5, I wish to convert it to 5. Error message: error: invalid operands to binary % (have ‘float’ and ‘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;
}
Was it helpful?

Solution

Do it like this:

int round_zero_digits(float x)
{
  return x + 0.5;
}

Or more general:

#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;
}

With round_n_digits(x, 0) being equivalent to round_zero_digits(x).

Update (not using the math lib):

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;
}

Update^2 (the pure C'ish way):

#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;
}

With ROUND_ZERO_DIGITS() being the macro'ed version of the function round_zero_digits().

OTHER TIPS

Try this:

int round_up(float x)
{
    if ( (int) x == x ) return x;
    else return x + 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top