小编Geo*_*giD的帖子

将双精度数赋值给C中的int变量的非直观结果

有人可以给我一个解释,为什么我得到两个不同的数字,分别是.在图14和15中,作为以下代码的输出?

#include <stdio.h>  

int main()
{
    double Vmax = 2.9; 
    double Vmin = 1.4; 
    double step = 0.1; 

    double a =(Vmax-Vmin)/step;
    int b = (Vmax-Vmin)/step;
    int c = a;

    printf("%d  %d",b,c);  // 14 15, why?
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望在两种情况下都能获得15分,但似乎我缺少一些语言的基础知识.

我不确定它是否相关,但我在CodeBlocks中进行测试.但是,如果我在某些在线编译器中键入相同的代码行(例如这个),我会得到两个打印变量的答案为15.

c floating-point type-conversion implicit-conversion

47
推荐指数
4
解决办法
2971
查看次数