In my program the user inputs the number of decimal places he requires in an output. I save this input as deci. How do I use this variable deci as a precision modifier?
Sample: Input a number: 23.6788766 Input number of decimals: 2 Output: 23.67
In my program the user inputs the number of decimal places he requires in an output. I save this input as deci. How do I use this variable deci as a precision modifier?
Sample: Input a number: 23.6788766 Input number of decimals: 2 Output: 23.67
如果是 C,你可以这样做:
float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
在 C 中,例如将 6 位的默认精度更改为 8:
int precision = 8;
printf("%.*f\n", precision, 1.23456789);
精度参数必须是类型int
。
您可以使用 * 修饰符,如下面的 Wikipedia 示例中解释的那样:
printf("%*d", 5, 10) 将导致打印“ 10”,总宽度为 5 个字符,而 printf("%.*s", 3, "abcdef") 将导致打印 "abc" “正在打印。