在printf中使用%d来打印浮点值会产生意外的输出 [英] Use of %d inside printf to print float value gives unexpected output

查看:163
本文介绍了在printf中使用%d来打印浮点值会产生意外的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我在dev c ++中执行以下代码时,其输出为-536870912。
当我在在线教程的编译器上执行相同的代码时,每次运行都会有所不同。可能是什么原因?

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?

推荐答案

如果参数与格式说明符不匹配,则为 未定义的行为 。 Ue %f 打印浮点数。

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

printf("%f",f);

使用良好的编译器,您应该可以轻松捕获此类错误。 GCC产生:

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=]

您的代码。

PS: stdio.h 标头包含一个散点。

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

这篇关于在printf中使用%d来打印浮点值会产生意外的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆