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

c - Use of %d inside printf to print float value gives unexpected output

#include<iostream>
#include<stdio.h.>
using namespace std;
int main()
{
    float f=11.11;
    printf("%d",f);
}

When i execute the following code in dev c++ it gives the output -536870912. When i execute the same code on online tutorials point compiler i get different on every run. What could be the reason behind?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If the argument doesn't match the format specifier, it's undefined behaviour. Ue %f to print a float.

printf("%f",f);

You should be able to catch these sort of errors easily with good compilers. GCC produces:

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

for your code.

P.S.: There's a stray dot in your stdio.h header inclusion.


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

...