在printf格式和参数不一致 [英] Format and arguments inconsistency in printf

查看:192
本文介绍了在printf格式和参数不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下code:

#include <stdio.h>
int main(){
    printf("%f", 5);
    printf("%d", 5.01);
}

第一条语句将打印0.000000和第二条语句将打印大量。

The first statement will print 0.000000 and the second statement will print a large number.

我以为看到的printf格式%F就会弹出堆栈从一个4字节的说法。然后,我查阅了一些引用说printf函数将转变成浮动双,因此8字节的说法。因此,我认为它可能会打印出一张未predictable值。但是,怎么会打印出0.000000。

I thought the printf see the format %f will pop a 4-byte argument from stack. Then I looked up some references that say the printf function will transform float into double, so 8-byte argument. So I thought it may print out a unpredictable value. But how could it print out a 0.000000.

第二个也weired。 5.01二进制格式应为0 10000001 01000000101000111101100(0x40A051EC),它应该是1084248556十进制格式,但声明的结果是1889785610.为什么出现这种情况?

The second one is also weired. The binary format for 5.01 should be 0 10000001 01000000101000111101100 (0x40A051EC), It should be 1084248556 in decimal format, but the result of the statement is 1889785610. Why is this happen?

推荐答案

这是混乱的,但%d个是一个整数的格式,如%I (多数人期望它是双,因为%F 是浮动的,但它不是)。你不能用双使用它,你必须使用%F 。同样的,%F ,您不能使用它的整数;您必须使用float或double。

This is confusing, but %d is the format for an integer, like %i (most people expect it to be for double since %f is for float, but it's not). You can't use it with a double, you must use %f. Same with %f, you can't use an integer with it; you must use a float or double.

此外,的printf 不检查你使用它的类型,它只是一味地间$ P $点字节作为你告诉它你给它的类型。使用错误类型的错误类型说明符产生不确定的行为这就是为什么你看到你是什么。

Also, printf doesn't check the types you use it with, it just blindly interprets bytes as the types you tell it you gave it. Using the wrong types with the wrong type specifiers yields undefined behaviour which is why you're seeing what you are.

这篇关于在printf格式和参数不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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