c - 为什么以下代码的输出为零?

标签 c printf addition output

main()
{
    float a=10;
    float c;
    float b=5.5;
    c=a+b;
    printf("%d",c);
}

上面代码的输出为零。这是为什么呢?如果这是一些非常简单的 C 概念,我很抱歉,我是一个初学者。

最佳答案

您需要使用 %f (或 %e%g,具体取决于您的首选格式)而不是 % d 表示 float 。事实上,对非整数使用 %d 是“未定义的行为”。

printf("%f", c);

或者,如果您尝试将浮点舍入为整数,则必须先对其进行强制转换。

printf("%d", (int) c);

关于c - 为什么以下代码的输出为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431806/

相关文章:

c - CC/GCC 但不是 G++ (C/SDL2/Linux) 的奇怪段错误

c - 错误: invalid type argument of '->' - Printing the address of a struct field that is also a struct

python - 为什么 Python 将加法运算符的连续重复视为单次重复?

c - sigprocmask 之后 sigset_t 的值

c - 如何将二维数组从一维数组中转换出来?

c - printf 中使用的符号

c - fgetc 打印错误的字符到控制台

java - 通过 Netbeans 向数据库添加值

javascript - jquery json返回数据加两个数

c - 仅解析给定参数中的数字