开发者

What's the correct way to sprintf a float?

I'm trying to printf/sprintf floats using this code:

sprintf(buff, "FPS: %d\n%.4f N %.4f E\nAl: %.1fm Rl: %.1f\n", fps, p_viewer.p.lat, p_viewer.p.lon, p_viewer.p.alt, p_viewer.roll);

However I'm getting these warnings when I do so:

gfx_game_engine.c:300: warning: format '%.4f' expects type 'double', but argument 4 has type 'float'
gfx_game_engine.c:300: warning: format '%.4f' expects type 'double', but argument 5 has type 'float'
gfx_game_engine.c:300: warning: format '%.1f' expec开发者_运维知识库ts type 'double', but argument 6 has type 'float'
gfx_game_engine.c:300: warning: format '%.1f' expects type 'double', but argument 7 has type 'float'

What's the correct way to sprintf a float? Is there a special format character? I feel that the compiler might be casting the types somehow and this might contribute to it slowing down.

I'm using a dsPIC33FJ128GP802 microcontroller and compiling with MPLAB C30, a variant of GCC v3.23.


Your variant of gcc is broken. In the C language, there is no way to pass a float to a variadic function. Default promotions of small types (char, short, and float) up to at least int/double always apply. I'm guessing whoever hacked gcc for this microcontroller did something to disable promotions, probably with the idea that double is slow or hard to pass. You should flame them to hell and back. The correct solution, if a compiler vendor does not want to support double correctly, is to make all the floating point types the same size and equivalent to float, not to violate the promotion rules of the language.

Another idea: It's also possible that the prototype for sprintf is missing or wrong, for instance int sprintf(); instead of int sprintf(char *, const char *, ...);


float arguments should automatically be converted to double. There seems no other way to print a float. Your compiler shouldn't complain in this case.


Unlike for scanf, where %f means float and %lf means double, printf does not distinguish between them. So if printf (or its variants) are implemented via a library linkage, the compiler will have to convert.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜