Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c - How to use %d as a decimal integer with %f in the same line?

I want to design a function to print the first X(where X is an integer) digits after the decimal(from 0 to X) for a floating point number Y. For eg. print_num(12.123456,4) should give:

   12.0000000
   12.1000000 
   12.1200000
   12.1230000
   12.1234000

Here is a program that I tried to write:

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

But it just prints the output as it is:

%df
%df
%df
%df
%df
%df

I want to know how I can use %d as an integer with %f on the same line.

question from:https://stackoverflow.com/questions/65924470/how-to-use-d-as-a-decimal-integer-with-f-in-the-same-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a * in place of the precision. Then you can pass it an an int argument:

printf("%.*f
", i, N);

This doesn't print any trailing zeros, but you can add that as follows:

for (i=0;i<X;i++) {
    printf("%#.*f", i, N);
    if (i<X) printf("%0*d", X-i, 0);
    printf("
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...