预习C语言的round函数

C99标准中有round()函数,声明为:
double round(double );

返回距离参数最近的整数,如果参数值正好在两个整数的中间位置,则返回距离0较远的那一个整数(即正数则返回大于参数的整数,负数则返回小于参数的整数)

函数原型:

double round(
double x
);
float round(
float x
); // C++ only
long double round(
long double x
); // C++ only
float roundf(
float x
);
long double roundl(
long double x
);

使用示例:

// crt_round.c
// Build with: cl /W3 /Tc crt_round.c
// This example displays the rounded results of
// the floating-point values 2.499999, -2.499999,
// 2.8, -2.8, 2.5 and -2.5.

#include <math.h>
#include <stdio.h>

int main( void )
{
double x = 2.499999;
float y = 2.8f;
long double z = 2.5;

printf("round(%f) is %.0f\n", x, round(x));
printf("round(%f) is %.0f\n", -x, round(-x));
printf("roundf(%f) is %.0f\n", y, roundf(y));
printf("roundf(%f) is %.0f\n", -y, roundf(-y));
printf("roundl(%Lf) is %.0Lf\n", z, roundl(z));
printf("roundl(%Lf) is %.0Lf\n", -z, roundl(-z));
}

输出:

round(2.499999) is 2
round(-2.499999) is -2
roundf(2.800000) is 3
roundf(-2.800000) is -3
roundl(2.500000) is 3
roundl(-2.500000) is -3

如果

编译器报错  undefined reference to `round'

在cmake中添加这个库就可以了。

posted @ 2020-09-10 14:14  谁说的爱  阅读(1616)  评论(0)    收藏  举报