C / C++ 如何保留两位小数

转载:https://blog.csdn.net/qq_36667170/article/details/79265224

目录

首先说C++代码

 

然后说C的代码

 

深入理解


首先说C++代码

#include <iostream> 
#include <iomanip>  //不要忘了头文件
using namespace std;
int main(){
	//第一种写法
	cout<<setiosflags(ios::fixed)<<setprecision(2);
	//第二种写法
	cout.setf(ios::fixed);
	cout<<setprecision(2);
	//第三种写法
	cout<<fixed<<setprecision(2);
}
  • 要保留几位小数setprecision(n)的括号里n就换成几。
  • 前两种写法是一样的,第三种是简化写的。
  • 上面的语句写一次就行了,对之后的数字都有效。

 

然后说C的代码

%f 格式化输出浮点型数据,在%之后加上“.n”即可。例如:

#include  <stdio.h>
int main()
{
	float PI=3.1415926;
	float R=5.3;
	printf("面积 = %.2f\n", PI * R * R); //输出:面积 = 88.25
	printf("面积 = %f\n", PI * R * R);   //输出:面积 = 88.247337
	printf("面积 = %.8f\n", PI * R * R); //输出:面积 = 88.24733734
        return 0;
}

  • %.2f\n中的“.2”即保留两位小数
  • //不设定保留几位小数,则默认六位

 

深入理解


1.首先解释一下“语句写一次就行了,对之后的数字都有效”。

在s之后设置保留两位小数之后,重新声明另一个数,输出依旧显示两位小数。所以设置精度语句只需写一次就可以了。

#include <iostream>
#include <iomanip>   //设置必备的头文件
using namespace std;
int main()
{
	double s=12.345;
	cout<<setiosflags(ios::fixed)<<setprecision(2);
	cout<<s<<endl;		//输出12.35

    float pi=3.14159;
	cout<<pi<<endl;		//输出3.14
	return 0;
}

2.setprecision(n)
   功能:控制浮点数显示的有效数字个数。

图中可以看

  • 由8-9两行代码可以看出,也是只写一次就可以。
  • 8-10行可以看出,只是四舍五入修改了数字的显示方法,并不是修改原数字。从常识我们可以知道,如果12.345数字本身改变,那就是两位有效数字变为 12,那从两位有效数字改为四位有效数字会变为 12.00,而不是12.34。
  • 11-12行可以看出如果要保留的太多,是不会补上0的(往下看有补0的方法)。
  • 13行中可以看出,如果小数点前的位数多于你要保留位数,则会使用科学计数法。
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
	double s=12.345;
	
	cout<<setprecision(2)<<s<<endl;
	cout<<s<<endl;
	cout<<setprecision(4)<<s<<endl;
	cout<<setprecision(6)<<s<<endl;
	cout<<setprecision(8)<<s<<endl;
	cout<<setprecision(1)<<s<<endl;
	
	return 0;
} 


3.补充一小点showpoint

#include <iostream>
#include <iomanip>   
using namespace std;
int main()
{
	double s=12.345;
	cout<<s<<endl;    //输出原数12.345
	cout<<setprecision(2);
	cout<<s<<endl;    //输出保留两位有效数字12
    cout.setf(ios::showpoint); //或者写cout<<setiosflags(ios::showpoint);
    cout<<s<<endl;    //输出保留两位有效数字外加一个小数点12.
    
	return 0;
}


  
  这是在尝试过程中发现的一个无聊操作,如果12.34保留两位有效数字,会显示12,但是你可以经过这个操作让它显示12. 注意有个“.”


4.fixed
  setprecision(n)和fixed合用的话可以控制小数点后有几位。
  只要加上以下任意一个语句就可以。

cout<<setiosflags(ios::fixed);
cout.setf(ios::fixed);
cout<<fixed;

然后你会发现,如果你要保留的位数多于数字原来的小数,就会补上0。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	double s=12.345;
	cout.setf(ios::fixed);
	cout<<setprecision(1)<<s<<endl;
	cout<<setprecision(3)<<s<<endl;
	cout<<setprecision(5)<<s<<endl;
	
	return 0;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值