首页 > 解决方案 > 改变格式说明符的位置如何改变 ac 程序的输出?

问题描述

我的代码是:

#include<stdio.h>
#include<math.h>

int main()
{
    int c = pow(3,2);

    printf("%f   %f   %d \n\n",pow(3,2),c,c);
    printf("%f   %d   %f \n\n",pow(3,2),c,c);

    return 0;
}

输出是:

9.000000   0.000000   4200688

9.000000   9   0.000000

谁能解释为什么在输出的第一行而不是打印 9 (就像在输出的第二行一样)它打印 4200688 (可能是垃圾值)?

标签: cpow

解决方案


您提到的代码具有未定义的行为。阅读pow功能手册页并检查它的原型。它说

双 pow(双 x,双 y);

在这份声明中

int c = pow(3,2);

并使用正确的格式说明符,并且在使用标志编译时不要播放编译器警告-Wall,听警告。

warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Werror=format=]
          printf("%f   %f   %d \n\n",pow(3,2),c,c);
warning: format ‘%f’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Werror=format=]
     printf("%f   %d   %f \n\n",pow(3,2),c,c);

来自 C99 标准第 7.19.6.1 节

如果任何参数不是相应转换规范的正确类型,则行为未定义。


推荐阅读