在浮动小数printf的可变数目 [英] Printf variable number of decimals in float

查看:136
本文介绍了在浮动小数printf的可变数目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有趣的格式打印nonterminated固定长度字符串是这样的:

 字符中newstr [40] = {0};
sprintf的(中newstr,%*第的sizeof(myStr中),myStr的);

所以,我想,也许是有打印浮点数的printf麾下的方式...


  

%8.2f


不得不选择小数点后的位数与整数能力。

事情是这样的:

 的sprintf(myStr中,%D%F,numberofdecimals,floatnumbervalue)

编辑 - 解决方案:结果
(四舍五入和清除浮点数到所需的precision)。

  INT precision = 2;
焦炭kolf [16] = {0};
sprintf的(kolf,%8. * F,precision,mystruct.myfloat);
浮KOL = ATOF(kolf);


解决方案

您也可以使用。*浮动点,也<见href=\"http://www.cplusplus.com/reference/cstdio/printf/\">http://www.cplusplus.com/reference/cstdio/printf/ (指的是C ++,但格式说明是类似的)


  

.number :对于A,E,E,F和F说明符:这是数字是多少
  小数点后打印(默认情况下,这是6)。


  
  

...


  
  

* :不格式字符串指定的precision,但作为一个
  额外的整数值参数preceding有给个说法
  被格式化。


例如:

 浮动floatnumbervalue = 42.3456;
INT numberofdecimals = 2;
的printf(%* F,numberofdecimals,floatnumbervalue);

输出:

  42.35

I found interesting format for printing nonterminated fixed length strings like this:

char newstr[40] = {0};
sprintf(newstr,"%.*s",  sizeof(mystr), mystr);

So I think maybe is there a way under printf command for printing a float number...

"%8.2f"

to have ability to choose number of decimals with integer number.

Something like this:

sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)

EDIT - Solution:
(for rounding and clearing a float number to desired precision).

int precision = 2;  
char kolf[16] = {0};  
sprintf(kolf, "%8.*f", precision, mystruct.myfloat);  
float kol = atof(kolf);  

解决方案

You can also use ".*" with floating points, see also http://www.cplusplus.com/reference/cstdio/printf/ (refers to C++, but the format specifiers are similar)

.number: For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).

...

.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

For example:

float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);

Output:

42.35

这篇关于在浮动小数printf的可变数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆