c - Printf 中的类型转换

标签 c gcc type-conversion printf

<分区>

代码段的o/p:

printf("%f", 9/5);
  1. 在我的 linux gcc 4.6.3 中(gcc myprog.c 后跟 ./a.out):

    -0.000000

  2. 在 codepad.org 中:

    2.168831

为什么不同?

我已经引用了链接:Why cast is needed in printf?Implicit conversion in C? , 但无法使用它。

关于键盘执行的信息: C: 海湾合作委员会 4.1.2 标志:-O -fmessage-length=0 -fno-merge-constants -fstrict-aliasing -fstack-protector-all

编辑: 更多的: 用于在(在同一程序中)键盘中执行以下操作

printf("%f\n", 99/5);
printf("%f\n", 18/5);
printf("%f\n", 2/3);
printf("%f\n%f\n%f", 2, 3, 4);
printf("%f\n", 2);

O/P 是

2.168831
2.168831
2.168831
0.000000
0.000000
-0.001246
-0.0018760.000000

前三个输出是相同的垃圾值(而不是最后一个)。想知道为什么。

最佳答案

9/5 被视为一个 int .. 当您使用格式说明符 %f (期望为 double )时会导致未定义的输出

要打印正确的结果,请执行以下操作:

printf("%f", 9.0/5); // forces system to make sure that the argument is not treates as int

printf("%f\n",(double)9/5); // type casting the argument to a double .. this is more helpful 
                            // in case you have a variable

我不确定 codepad.org 是如何编译他们的代码的……但是对于 gcc,您必须为 printf 提供正确的参数以匹配格式说明符


请考虑以下内容以更仔细地查看:

#include <stdio.h>
int main(){ 
    printf("%f %d %f\n",9/5,9/5,9.0/5);
    printf("%f\n",1); // as suggested by devnull-again since the argument is not a double
                      // the output is undefined
    return 0;
}

输出:

$ ./test
0.000000 1 1.800000
0.000000

关于c - Printf 中的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19889087/

相关文章:

c - 当我们使用 array[i,j] 访问 c 中的元素时会发生什么?

c++ - 如何通过cout将字符输出为整数?

c - Intel x86 到 ARM 汇编转换

c - c编译器如何处理无符号和有符号整数?为什么无符号和有符号算术运算的汇编代码相同?

c++ - 访问 map<int,string[4]> 中的元素

c# - 如何在 C# 中将对象数组转换为 double 组

mysql - 更新/修复字符串中的列数据类型和记录以按 mysql innoDB 数据库中的数字数据类型排序

c - 如何检查 long long 是否可以放入 double 变量

C/POSIX- pthread_t 阻塞直到任务完成

c - GCC 中的动态分配指针数组不匹配