#include <stdio.h> /* printf */
#include <math.h> /* round, floor, ceil, trunc */
inline int myIntRound(double dInput)
{
if(dInput >= 0.0f)
{
return ((int)(dInput + 0.5f));
}
return ((int)(dInput - 0.5f));
}
double d[]={-1.5, -0.7, -0.5, -0.3, 0.3, 0.5, 0.7, 1.5, 1.9};
int print_doubles(double d[], int n)
{
printf("original ");
for(int i=0;i<n;i++)
printf (" %f", d[i]);
printf(" ");
}
//直接int会舍弃浮点部分,只取整数
int print_int_doubles(double d[], int n)
{
printf("int ");
for(int i=0;i<n;i++)
printf (" %f", double(int(d[i])));
printf(" ");
}
int print_round_doubles(double d[], int n)
{
printf("round ");
for(int i=0;i<n;i++)
printf (" %f", round(d[i]));
printf(" ");
for(int i=0;i<n;i++)
printf (" %d", int(round(d[i])));
printf(" ");
}
int print_ceil_doubles(double d[], int n)
{
printf("ceil ");
for(int i=0;i<n;i++)
printf (" %f", ceil(d[i]));
printf(" ");
}
int print_floor_doubles(double d[], int n)
{
printf("floor ");
for(int i=0;i<n;i++)
printf (" %f", floor(d[i]));
printf(" ");
}
int print_trunc_doubles(double d[], int n)
{
printf("trunc ");
for(int i=0;i<n;i++)
printf (" %f", trunc(d[i]));
printf(" ");
}
//和round
int print_myint_doubles(double d[], int n)
{
printf("myint ");
for(int i=0;i<n;i++)
printf (" %d", myIntRound(d[i]));
printf(" ");
}
int main ()
{
print_doubles(d, sizeof(d)/sizeof(d[0]));
print_int_doubles(d, sizeof(d)/sizeof(d[0]));
print_round_doubles(d, sizeof(d)/sizeof(d[0]));
print_floor_doubles(d, sizeof(d)/sizeof(d[0]));
print_ceil_doubles(d, sizeof(d)/sizeof(d[0]));
print_trunc_doubles(d, sizeof(d)/sizeof(d[0]));
print_myint_doubles(d, sizeof(d)/sizeof(d[0]));
return 0;
}
/*
:! ./round
original
-1.500000 -0.700000 -0.500000 -0.300000 0.300000 0.500000 0.700000 1.500000 1.900000
int
-1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000 1.000000
round
-2.000000 -1.000000 -1.000000 -0.000000 0.000000 1.000000 1.000000 2.000000 2.000000
-2 -1 -1 0 0 1 1 2 2
floor
-2.000000 -1.000000 -1.000000 -1.000000 0.000000 0.000000 0.000000 1.000000 1.000000
ceil
-1.000000 -0.000000 -0.000000 -0.000000 1.000000 1.000000 1.000000 2.000000 2.000000
trunc
-1.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 1.000000 1.000000
myint
-2 -1 -1 0 0 1 1 2 2
*/
测试后可以发现,直接int转换不行,会丢失浮点部分。 要用+0.5或-0.5方式。 或者用round函数