I'm a bit confused about the round()
function in C.
First of all, man says:
SYNOPSIS
#include <math.h>
double round(double x);
RETURN VALUE
These functions return the rounded integer value.
If x is integral, +0, -0, NaN, or infinite, x itself is returned.
The return value is a double
/ float
or an int
?
In second place, I've created a function that first rounds, then casts to int. Latter on my code I use it as a mean to compare doubles
int tointn(double in,int n)
{
int i = 0;
i = (int)round(in*pow(10,n));
return i;
}
This function apparently isn't stable throughout my tests. Is there redundancy here? Well... I'm not looking only for an answer, but a better understanding on the subject.
If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places. If num_digits is 0, the number is rounded to the nearest integer. If num_digits is less than 0, the number is rounded to the left of the decimal point. To always round up (away from zero), use the ROUNDUP function.
The round() function rounds a number to the nearest whole number. The math. ceil() method rounds a number up to the nearest whole number while the math. floor() method rounds a number down to the nearest whole number.
Use the lround Function to Round Floating-Point Number to the Nearest Integer and Return Integral Type.
Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.) round toward 0 meaning . 5 or greater => round up 0 to .
If you want a long integer to be returned then please use lround
:
long int tolongint(double in)
{
return lround(in));
}
For details please see lround which is available as of the C++ 11 standard.
The wording in the man-page is meant to be read literally, that is in its mathematical sense. The wording "x is integral" means that x is an element of Z, not that x has the data type int
.
Casting a double
to int
can be dangerous because the maximum arbitrary integral value a double
can hold is 2^52 (assuming an IEEE 754 conforming binary64 ), the maximum value an int
can hold might be smaller (it is mostly 32 bit on 32-bit architectures and also 32-bit on some 64-bit architectures).
If you need only powers of ten you can test it with this little program yourself:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int i;
for(i = 0;i < 26;i++){
printf("%d:\t%.2f\t%d\n",i, pow(10,i), (int)pow(10,i));
}
exit(EXIT_SUCCESS);
}
Instead of casting you should use the functions that return a proper integral data type like e.g.: lround(3)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With