Home c++ rounding using elementary arithmetic operations

rounding using elementary arithmetic operations

Author

Date

Category

How to perform rounding using elementary arithmetic operations?
Need to perform rounding to the nearest whole
I have the following code:

int main ()
{
  Double x;
    COUT & LT; & LT; "VVedite Neceloe Chislo =";
  CIN & GT; & GT; x;
    COUT & LT; & LT; "Celaya Chast 'Chisla =";
  // We get a whole part of the number x
  if (x & gt; = 0) cout & lt; & lt; Floor (x) & lt; & lt; Endl;
  if (x & lt; 0) cout & lt; & lt; CEIL (Fabs (X)) & lt; & lt; Endl;
    COUT & LT; & lt; "Okryglennoe do blizhajshego =";
  // The number X, rounded to the nearest whole
  if (x & gt; = 0) cout & lt; & lt; Floor (x) & lt; & lt; Endl;
  if (x & lt; 0) cout & lt; & lt; Ceil (x) & lt; & lt; Endl;
SYSTEM ("PAUSE");
  Return 0;}

Answer 1, Authority 100%

Well, for example …

rounded the number “pi” to three marks after the comma.

double pi = 3.14159265358;
pi = int (pi * 1000 + 0.5) /1000.0;

arrange? 🙂

p.s. You would somehow write more accurately – what numbers, the range, type, how to round – to more, to a smaller, to the nearest … And so – guess what you wanted: (

Update

to the nearest whole – it is rude, up to 0 signs after a comma – so just

int (x + ((x & lt; 0)? -0.5: 0.5))

And in general, this is done by the standard function Round ()

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions