Simple C++ program to round given number away from zero.

#include <iostream>
#include <cmath>

using namespace std;

// 2018 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net
double roundAwayFromZero(double x, int n);

int main() {
  double x = 0;
  int n = 0;

  cout << "Enter x: ";
  cin >> x;


  cout << "Enter n: ";
  cin >> n;

  cout << "roundAwayFromZero(" << x << ", " << n << ") is equal to " << roundAwayFromZero(x, n);

  int a;
  cin >> a;

  return 0;
}

double roundAwayFromZero(double x, int n) {
  return x > 0 ? ceil(pow(10, n) * x) / pow(10, n) : floor(pow(10, n) * x) / pow(10, n);
}
IN
3.1425 2
-3.1425 2
OUT
3.15
-3.15

 



C++ Round Away From Zero
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close