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
499 views
in Technique[技术] by (71.8m points)

printf - Simple use of sprintf - C

I'm trying to work out why a larger problem is occurring, using a smaller program as an example. This smaller program does not work, leading me to believe it is my understanding of the function that is flawed.

As far as I (had) believed, the following program should initialise a string with up to 30 characters, then take the number '5' to nine significant figures, and turn it into that string. The program should then print the value '5.00000000'. However, the program prints the value 7.96788(...). Why is this?

#include <stdio.h>

int main()
{
    char word[30];
    sprintf(word, "%.9g", 5);
    printf(word);
    return 0;
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is because 5 is an integer (int), and you're telling sprintf to pretend that it's a double-precision floating-point number (double). You need to change this:

sprintf(word,"%.9g", 5);

to either of these:

sprintf(word,"%.9g", 5.0);
sprintf(word,"%.9g", (double) 5);

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

2.1m questions

2.1m answers

60 comments

56.8k users

...