预习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中添加这个库就可以了。

原文链接: https://www.cnblogs.com/chen-le23/p/13645412.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    预习C语言的round函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/202570

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午9:12
下一篇 2023年2月12日 下午9:12

相关推荐