如何在同一行中使用 %d 作为十进制整数与 %f ?

pla*_*ice 2 c floating-point printf

我想设计一个函数来打印浮点数 Y 的小数点后的第一个 X(其中 X 是整数)数字(从 0 到 X)。例如。 print_num(12.123456,4) 应该给:

   12.0000000
   12.1000000 
   12.1200000
   12.1230000
   12.1234000
Run Code Online (Sandbox Code Playgroud)

这是我尝试编写的程序:

#include<stdio.h>
void printplaces(float N,int X)
{
    for(int i =0;i<=X;i++)
    {
        printf("%.%df\n",N,i);
    }
}
void main()
{
    printplaces(23.23423342,5);
}
Run Code Online (Sandbox Code Playgroud)

但它只是按原样打印输出:

%df
%df
%df
%df
%df
%df
Run Code Online (Sandbox Code Playgroud)

我想知道如何将 %d 作为整数与 %f 在同一行上使用。

dbu*_*ush 5

您可以使用 a*代替精度。然后你可以给它传递一个int参数:

printf("%.*f\n", i, N);
Run Code Online (Sandbox Code Playgroud)

这不会打印任何尾随零,但您可以添加如下:

for (i=0;i<X;i++) {
    printf("%#.*f", i, N);
    if (i<X) printf("%0*d", X-i, 0);
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)