简体   繁体   English

在C中加倍到int

[英]double to int in c

I have this code : 我有这个代码:

#include <stdio.h>

int main ()
{
    double d = 10;
    int x = 5;

    x = (int) d + x;
    d = (double)x + d;

    printf("%lf\n" , d);
    printf("%d\n" , x);
}

the out put is : 输出是:

-0.0000
15

Why is this working for int but not for double ? 为什么这为int而不是double起作用? How to make this work? 如何使这项工作?

In C89 use %f format specifer to print double value. 在C89中,使用%f格式说明符打印double精度值。 With newer standards you might use %lf , in which case l has no effect (it was introduced for symmetry with scanf() ), but it's just asking for trouble, as it's undefined in previous standard. 在较新的标准中,您可能会使用%lf ,在这种情况下, l无效(它是为与scanf()对称而引入的),但这只是自找麻烦,因为以前的标准中未定义。

#include <stdio.h>

int main(void)
{
    double d = 10;
    int x = 5;

    x = (int) d + x;
    d = (double)x + d;

    printf("%f\n", d);
    printf("%d\n", x);

    return 0;
}

Note that in C89 you probably should add return 0; 注意,在C89中,您可能应该添加return 0; . With C99/C11 return 0; 用C99 / C11 return 0; is implicitly added when omitted (with exception to call of exit() function directly in main() , which serves for that as well). 在省略时隐式添加(除了直接在main()调用exit()函数的例外,该函数也可以这样做)。

Works fine for me 对我来说很好

http://ideone.com/YBfHau http://ideone.com/YBfHau

    #include <stdio.h>

int main ()
{
    double d = 10;
    int x = 5;

    x = (int) d + x;
    d = (double)x + d;

    printf("%lf\n" , d);
    printf("%d" , x);
return 0;

}

EDIT: Remember to add return 0 编辑:记得添加return 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM