(C++) How would I display a value rounded to the nearest integer?

  • Context: C/C++ 
  • Thread starter Thread starter soul5
  • Start date Start date
  • Tags Tags
    Integer Value
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 18K views
soul5
Messages
63
Reaction score
0
Like for example

Prompting message reads.

"Please enter a positive value"

Example:

Please enter a positive value: 234.7
Rounded to the nearest integer the number is: 235


Please enter a positive value: 10.3
Rounded to the nearest integer the number is: 10


What I have

int num;

count<< "Please enter a positive value";

cin>> num;

count<< num << endl;




The problem is that doesn't round the number to the nearest interger so what would I do to round it?
 
Physics news on Phys.org
soul5 said:
Like for example

Prompting message reads.

"Please enter a positive value"

Example:

Please enter a positive value: 234.7
Rounded to the nearest integer the number is: 235


Please enter a positive value: 10.3
Rounded to the nearest integer the number is: 10


What I have

int num;

count<< "Please enter a positive value";

cin>> num;

count<< num << endl;




The problem is that doesn't round the number to the nearest interger so what would I do to round it?

(int) (3.5+0.5)
 
rootX said:
(int) (3.5+0.5)

Dude that's not it.
 
Last edited:
It does help if num is a floating point variable, rather than an int.

Round to zero (truncation)
Code:
int rounded_num = static_cast<int>(num);

Round to +infinity
Code:
int rounded_num = std::floor(num + 0.5);

Round away from zero
Code:
int rounded_num = (num < 0.0)
    ? ((std::floor(num) == num - 0.5) ? std::floor(num) : std::floor(num + 0.5))
    : std::floor(num + 0.5);
Really shouldn't do direct == with floating points, but that's another subject.

Or in C++0x:
Code:
int rounded_num = std::round(num);

Round to even
Um, have fun...
 
KTC said:
It does help if num is a floating point variable, rather than an int.

Round to zero (truncation)
Code:
int rounded_num = static_cast<int>(num);

Round to +infinity
Code:
int rounded_num = std::floor(num + 0.5);

Round away from zero
Code:
int rounded_num = (num < 0.0)
    ? ((std::floor(num) == num - 0.5) ? std::floor(num) : std::floor(num + 0.5))
    : std::floor(num + 0.5);
Really shouldn't do direct == with floating points, but that's another subject.

Or in C++0x:
Code:
int rounded_num = std::round(num);

Round to even
Um, have fun...
very insteresting, but I think rootx's answer is enough and simple.