加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用sprintf动态设置精度

发布时间:2020-12-16 05:20:03 所属栏目:百科 来源:网络整理
导读:使用sprintf和一般语法“%A.B”我可以这样做: double a = 0.0000005l;char myNumber[50];sprintf(myNumber,"%.2lf",a); 我可以在格式字符串中动态设置A和B吗? 解决方法 是的,你可以这样做.您需要使用星号*作为字段宽度,使用.*作为精度.然后,您需要提供带
使用sprintf和一般语法“%A.B”我可以这样做:
double a = 0.0000005l;
char myNumber[50];
sprintf(myNumber,"%.2lf",a);

我可以在格式字符串中动态设置A和B吗?

解决方法

是的,你可以这样做.您需要使用星号*作为字段宽度,使用.*作为精度.然后,您需要提供带有值的参数.就像是
sprintf(myNumber,"%*.*lf",A,B,a);

注意:A和B需要输入int.从C11标准,章节§7.21.6.1,fprintf()函数

… a field width,or precision,or both,may be indicated by an asterisk. In
this case,an int argument supplies the field width or precision. The arguments specifying field width,shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读