Hi,

I have an array with elements filled with values such as 36.0119. I am trying to find a way of rounding each value to the nearest whole number E.G. 36. To show i have attempted this i have used cout with the array and set precision which is ok but i need rounded results in my array. Researching this in books i found functions such as fabs, which is the best i have found. I cannot really show you any code towards this apart from:

a = centervalue+(scalefactor*(sin(pi*a/180)));
a = fabs(a);

cout << a; //using this to check results from fabs function

im sure a rounding function is easy! but i just cannot find it or get one to work!

thanks for looking

This is one way to do it.

int main ()
{
   float f = 123.457678F;

   int a = (int)f;
   float b = f - (int)f;
   if(b > 0.5F)
       a++;
   cout << a;
   return 0;
}

Or, a little easier:

int main ()
{
   float b;
   float f = 123.457678F;

   float b = (int) (f + 0.5);
   cout << b;
   return 0;
}

I also have values that need rounding down to get to the nearest like..whole number. Im amazed c++ dosnt have a function that can round to the nearest whole number, regardless of whether it needs rounded up or down.

Thanks for your posts

Or a little little easier:

int round(const double& c)
{ 
    if (c - (int)c > .5)
        return  (int)c + 1;
    else
        return (int)c;
}

I also have values that need rounding down to get to the nearest like..whole number. Im amazed c++ dosnt have a function that can round to the nearest whole number, regardless of whether it needs rounded up or down.

Thanks for your posts

The sine of 180 is 0. What's the problem?

I also have values that need rounding down to get to the nearest like..whole number. Im amazed c++ dosnt have a function that can round to the nearest whole number, regardless of whether it needs rounded up or down.

Thanks for your posts

Why? It's trivial. Languages don't need a function for every insignificant math concept.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.