0
Can someone please answer
How can we round to or round up to the nearest integer with decimal places number or fraction in C++?
2 Respostas
+ 4
Suppose this
double d = 2.54;
Here, you have 3 choices.
1. round up (ceil operation).
2. round down (floor operation).
3. round to the nearest int (adding 0.5 to d and casting it to int)
The first two are obvious enough so long as you include math header to your project and use ceil(d) and floor(d) functions.
The third one, has no built-in function, so you'd implement it as a utility function.
int round(double x) {
return static_cast<int>(x + 0.5);
}
int main() {
double d = 2.54;
int toInt = round(d);
}
+ 4
It's worthy to mention that, C language (particularly math.h header file) has numerous built-in round functions and macros to work with. See the following documentation.
Defined in header <math.h>
float roundf( float arg ); (1)(since C99)
double round( double arg ); (2)(since C99)
long double roundl( long double arg ); (3)(since C99)
Defined in header <tgmath.h>
#define round( arg ) (4)(since C99)
Defined in header <math.h>
long lroundf( float arg ); (5)(since C99)
long lround( double arg ); (6)(since C99)
long lroundl( long double arg ); (7)(since C99)
Defined in header <tgmath.h>
#define lround( arg ) (8)(since C99)
Defined in header <math.h>
long long llroundf( float arg ); (9)(since C99)
long long llround( double arg ); (10)(since C99)
long long llroundl( long double arg ); (11)(since C99)
Defined in header <tgmath.h>
#define llround( arg ) (12)(since C99)