c - 在 C 中将浮点数舍入到用户指定的小数位数
问题描述
如问题所示,如何将浮点数四舍五入到用户指定的小数点位数?我当前的代码仅将浮点数打印到小数点后 2 位。另外,是否有用于此目的的内置功能?
#include <stdio.h>
int main()
{
float x = 1.2345;
int dp;
printf("The float is: %f. How many decimal points to round to? ", x);
scanf("%d", &dp);
printf("Number: %.2f", x);
}
解决方案
您可以用*
字符代替精度,在这种情况下,下一个参数将指定精度。
printf("Number: %.*f", dp, x);
推荐阅读
- vue.js - 显示具有 id 的数组中的特定数据
- android - MotionLayout 中的 ViewPager 不显示项目
- mysql - ubuntu 20 上的专用服务器,带有 plesk obsidian 18.xx
- react-native - React Native Paper HelperText 在不可见时会占用空间
- python - 在 Windows 上使 Python 函数超时的最简单方法
- python - 如何使用自定义 CTC 层正确保存和加载模型(Keras 示例)
- html - 如何用空格开始网格?CSS
- wordpress - Cpanel 和 whm 被黑了但是
- android - 重新加载 Android Webview
- javascript - 如何在 vue js 中重用我的模态组件(重新渲染问题)