954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

rounding array elements

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[i] = centervalue+(scalefactor*(sin(pi*a[i]/180)));
a[i] = fabs(a[i]);

cout << a[i]; //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

johnnyjohn20
Newbie Poster
22 posts since Nov 2007
Reputation Points: 37
Solved Threads: 0
 

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;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Or, a little easier:

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

   float b = (int) (f + 0.5);
   cout << b;
   return 0;
}
WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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

johnnyjohn20
Newbie Poster
22 posts since Nov 2007
Reputation Points: 37
Solved Threads: 0
 

Or a little little easier:

int round(const double& c)
{ 
    if (c - (int)c > .5)
        return  (int)c + 1;
    else
        return (int)c;
}
Sturm
Veteran Poster
1,079 posts since Jan 2007
Reputation Points: 343
Solved Threads: 24
 

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 180is 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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You