c++保留有效位和小数位

##c++保留有效位和小数位
引用头文件iomanip;

#1.保留小数位:

#include<iostream>
#include<iomanip>
int main(){
	using namespace std;
	float f=312.159268908;
	//保留三位小数 
	cout << fixed << setprecision(3) << f << endl;
	
	//保留三位有效位
	
	//cout << setprecision(3) << f << endl;
	return 0; 
}

#输出结果:

在这里插入图片描述
#2.保留数据位:

#include<iostream>
#include<iomanip>
int main(){
	using namespace std;
	float f=312.159268908;
	//保留三位小数 
	//cout << fixed << setprecision(3) << f << endl;
	
	//保留三位有效位
	
	cout << setprecision(3) << f << endl;
	return 0; 
}

#输出结果:
在这里插入图片描述

C++保留小数位有多种实现方法,以下为你详细介绍: ### 自定义函数实现四舍五入保留指定位小数 通过自定义函数实现,其原理是将小数乘以一个合适的倍数,加上 0.5 进行四舍五入,再除以该倍数恢复到原量级。 ```cpp #include <iostream> #include <cmath> using namespace std; double round(double num, int n) { int x = (num + 0.5 * pow(10, -n)) * pow(10, n); double y = x / pow(10, n); return y; } int main() { int n = 3; double num = 3.1415926; cout << round(num, n); return 0; } ``` 该代码运行结果为 3.142,可将 `num` 保留 `n` 位小数并四舍五入输出 [^1]。 ### 使用 `<iomanip>` 库中的 `setprecision` `fixed` 操纵符 `setprecision` 用于设置输出的精度,`fixed` 用于指定以固定点表示法输出浮点数。 ```cpp #include <iostream> #include <iomanip> using namespace std; int main() { double pi = 3.141592653; cout << pi << endl; cout << fixed << setprecision(3) << pi << endl; return 0; } ``` 代码运行结果为 3.142,可将 `pi` 保留三位小数输出 [^1]。 ### 使用 `printf` 函数 `printf` 是 C 语言的标准输出函数,在 C++ 中也可使用,通过格式化字符串 `%.nf` 来指定保留 `n` 位小数。 ```cpp #include <iostream> using namespace std; int main() { double x = 8.67134; printf("%.3f", x); return 0; } ``` 该代码将 `x` 保留三位小数输出 [^2]。 ### 使用 `<stdio.h>` 头文件中的 `scanf` `printf` 通过 `scanf` 读取输入的浮点数,`printf` 按指定格式输出保留 `n` 位小数的结果。 ```cpp #include <stdio.h> int main() { double a; scanf("%lf", &a); printf("%.2lf", a); return 0; } ``` 此代码可读取用户输入的浮点数,并保留两位小数输出 [^4]。 ### 使用 `setprecision` `std::fixed` 组合 同样使用 `setprecision` 设置精度,`std::fixed` 指定固定点表示法,可保留指定的有效数字位数。 ```cpp #include <iostream> #include <iomanip> using namespace std; int main() { double x = 123.1235678; cout << setprecision(3) << std::fixed << x << endl; return 0; } ``` 该代码将 `x` 保留三位有效数字输出 [^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值