Simple use of sprintf - C

前端 未结 4 1361
夕颜
夕颜 2020-12-13 20:16

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 understa

相关标签:
4条回答
  • 2020-12-13 20:39

    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);
    
    0 讨论(0)
  • 2020-12-13 20:39

    Use 5.0 instead. 5 by itself is an integer and will get bitmangled into looking like a float, which is where your 7.xxxx comes from.

    0 讨论(0)
  • 2020-12-13 20:40

    I see two problems:

    1. As others already said, you have to specify a double instead of an int. Your compiler may have a switch to print out warnings in these cases (-Wall in gcc, for example).

    2. To print out 5.00..., you should use %f instead of %g.

    That gives sprintf(word,"%.9f", (double) 5); as correct syntax.

    0 讨论(0)
  • 2020-12-13 20:44

    Or you can change the descriptor format: "%.9d"

    0 讨论(0)
提交回复
热议问题