Rounding numbers

I am currently using this method.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
   double num = 12.456789;
   cout << num << '\n'; //Outputs 12.4568
   cout << fixed << num << '\n'; //Outputs 12.456789
   cout << setprecision(3) << fixed <<  num << '\n'; //Outputs 12.457
   return 0;
}


It work wonders but my class assignment requires me to use another body to display in the main. So this is what I have..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>

int main()
{
  //Rounding 
   cout << setprecision(3) << fixed << Round(4.5268) << '\n'; 
   return 0;
}

int Round(float a)
{
	return a;
}


I know what I have is completely wrong but how do I make the int Round(float a) in the main making it round?

Thanks
Last edited on
Your second piece of code should round the number, what seems to be the problem? To get standard rounding, try this function:

1
2
3
4
int Round(float a)
{
    return int(a+0.5);
}

Ohhhhhh

Jesus, I feel so stupid lol, thanks so much!
What about this?


int FunkyRound( float a );

// Rounds a to the nearest integer, but largest magnitude. i.e. -2.7 becomes -3, not -2.
You would have to check specifically for negative numbers, if a number is negative you would subtract 0.5 instead of adding. That should work.
Topic archived. No new replies allowed.