gpt4 book ai didi

c - 是否可以在 C 中以用户定义的精度在小数点后打印 float ?

转载 作者:行者123 更新时间:2023-11-30 15:37:47 25 4
gpt4 key购买 nike

我想在 C 中以用户定义的精度打印出小数点后的 float ,例如,

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);

然后打印带有 dec 位小数的数字 no

最佳答案

您可以格式化 float 的打印,但不能格式化其实际大小。

您可以阅读this关于格式化 float 。

为了节省时间,您可以使用 %f 格式说明符,如下所示

printf("%.PRECISIONf", fvar);

其中 PRECISION 是您想要的小数点后的位数,例如

int 
print_float(float fvar, unsigned int precision) {
char fs[32];
sprintf(fs,"%%.%df", precision);
return printf(fs, fvar);
}

调用例程时:

print_float(2.0f, 2);

您将得到 2.00 作为输出。

希望这能解决您的问题。

关于c - 是否可以在 C 中以用户定义的精度在小数点后打印 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22075857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com