栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++保留小数点后两位(floor&ceil&round)详解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++保留小数点后两位(floor&ceil&round)详解

 C++四舍五入保留小数点后两位  示例
#include 
using namespace std;
int main()
{
	double i = 2.235687;
	double j = round(i * 100) / 100;
	cout << "The original number is "  << i << endl;
	cout << "The keep two decimal of 2.235687 is "  << j << endl;
	system("pause");
	return 0;
}
 运行结果

函数解析见下面
 1、floor函数

功能:把一个小数向下取整
      即就是如果数是2.2,那向下取整的结果就为2.000000
原型:double floor(doube x);
    参数解释:
        x:是需要计算的数

示例
#include 
using namespace std;
int main()
{
    double i = floor(2.2);
    double j = floor(-2.2);
    cout << "The floor of 2.2 is " << i << endl;
    cout << "The floor of -2.2 is " << j << endl;
    system("pause");
    return 0;
}
运行结果 2、ceil函数

功能:把一个小数向上取整
      即就是如果数是2.2,那向下取整的结果就为3.000000
原型:double ceil(doube x);
    参数解释:
        x:是需要计算的数

示例
#include 
using namespace std;
int main()
{
    double i = ceil(2.2);
    double j = ceil(-2.2);
    cout << "The ceil of 2.2 is " << i << endl;
    cout << "The ceil of -2.2 is " << j << endl;
    system("pause");
    return 0;
}
 运行结果

3、round函数

功能:把一个小数四舍五入
      即就是如果数是2.2,那向下取整的结果就为2
                 如果数是2.5,那向上取整的结果就为3
原型:double round(doube x);
    参数解释:
        x:是需要计算的数

 示例
#include 
using namespace std;
int main()
{
    double i = round(2.2);
    double x = round(2.7);
    double j = round(-2.2);
    double y = round(-2.7);
    cout << "The round of 2.2 is " << i << endl;
    cout << "The round of 2.7 is " << x << endl;
    cout << "The round of -2.2 is " << j << endl;
    cout << "The round of -2.7 is " << y << endl;
    system("pause");
    return 0;
}
 运行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997649.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号