首页 > 编程语言 > 详细

预习C语言的round函数

时间:2020-09-10 14:48:52      阅读:84      评论:0      收藏:0      [点我收藏+]

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

预习C语言的round函数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!