对于实型的那些操作

 一、取整函数及应用

头文件:<cmath>

相关函数:floor( )——下取整       ceil( ) ——上取整

应用代码:

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int main()
{
/*取整问题*/
	double a=5.55624,b=4.44536,c=3.15243;
	a=(int)a;
	cout<<a<<endl;//可以看出强制转化只能保留整数位
	b=floor(b);
	cout<<b<<endl;//floor 下取整函数 
	c=ceil(c);
	cout<<c<<endl;//ceil 上取整函数
	return 0;
}
应用:四舍五入

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int main()
{
/*四舍五入*/
    double a=5.55624,b=4.44536,c=3.15243;
    if(floor(a+0.5)!=floor(a))cout<<ceil(a)<<endl;
    else cout<<floor(a)<<endl;//输出6,即五入 
    if(floor(b+0.5)!=floor(b))cout<<ceil(b)<<endl;
    else cout<<floor(b)<<endl;//输出4 ,即四舍 
	return 0; 
}

  二、保留几位小数及保留有效数字

头文件:<cstdio>  <iomanip> 

相关函数:printf(" ", );

<span style="font-family:Comic Sans MS;">#include <iostream>
#include <cstdio>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
	/*
	printf("%08.2f\n",x)
	8代表长宽为8;
	0代表不足位8不全
	.2代表精度为保留两位小数
	\n代表换行符 
	另:printf输出按照四舍五入的方式 
	*/
	float c=21.58;int x=4;
	printf("%0.2f\n",c);
	printf("%08.2f\n",c);
	printf("%04d\n",x);
	x=45;
	
	printf("%04d\n",x);//输出0045 
	x=4567; 
	printf("%04d\n",x);//输出4567
	x=45678; 
	printf("%04d\n",x);//输出45678
	c=0.0314159;
	printf("%8.5e\n",c);//科学计数法输出
	
	printf("%16d",x); //输出:“          46578”(有兴趣的话自己试一下这个) 
	
	//至于有效数字,本人实在不会c的,下面给出c++的,
	//如果那位大神知道c的可以在下面留言, 谢谢!
	//#include <iomanip>
	cout<<setprecision(3)<<c; //保留三位有效数字 
	cout<<fixed<<setprecision(3)<<c;//保留三位小数 
	
	return 0; 
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值