C中的浮点输出/输入问题

Num*_*tor -3 c floating-point

我希望您帮助理解以下内容:

对于代码:

int main() {
    int i=23;
    float f=7.5;

    printf("%f", i);
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

输出是0.000000,怎么不是7.500000

对于代码

int main() {
    int i=23;
    float f=7.5;

    printf("%d\n",f);
    printf("%f",i);
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

输出是1455115000, 7.500000.为什么不编译错误?这个号码是1455115000是什么?为什么现在正在印刷7.500000?

Car*_*rum 8

printf调用中不匹配的格式/参数会导致未定义的行为.如果您调高警告级别,编译器可能会告诉您.例如,clang为您的第一个程序提供此警告:

example.c:5:10: warning: conversion specifies type 'double' but the argument has
      type 'int' [-Wformat]
printf("%f", i);
        ~^   ~
        %d
Run Code Online (Sandbox Code Playgroud)

这些是你的第二个:

example.c:5:10: warning: conversion specifies type 'int' but the argument has
      type 'double' [-Wformat]
printf("%d\n",f);
        ~^    ~
        %f
example.c:6:10: warning: conversion specifies type 'double' but the argument has
      type 'int' [-Wformat]
printf("%f",i);
        ~^  ~
        %d
Run Code Online (Sandbox Code Playgroud)

这根本没有特别的标志. gcc默认情况下也会警告您的程序.例1:

example.c:5: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’
Run Code Online (Sandbox Code Playgroud)

例2:

example.c:5: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’
example.c:6: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’
Run Code Online (Sandbox Code Playgroud)

这两个编译器也警告你的隐含声明printf,但是我把这些消息留下了,因为它们与你的问题没有严格的关系.