2/12 的简单除法,双倍导致错误

Simple division of 2/12 with double causing errors

我不知道是什么导致了这个错误,我尝试用双精度除以 2/12,但它给了我一个完全错误的数字。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    double a;
    a = 2/12;
    printf("\n a = %lf  \n", a);
    return 0;
}

这个returns-272632568 并没有任何意义。谢谢你的帮助。

您在格式字符串中使用了 %d,但是 %d 表示整数而不是双精度。

您想使用 %f 代替 %d

详情请看这里:https://www.gnu.org/software/libc/manual/html_node/Table-of-Output-Conversions.html#Table-of-Output-Conversions

首先,你应该考虑声明:

double a = 2 / 12; // (integer)

它只会给你零,然后分配给双精度值,因为它们是整数。如果您使用:

double a = 2.0 / 12.0; // explicitly defining

然后您将使用以下语句获得正确的精度输出:

printf("\n a = %f\n", a);

或者,

printf("\n a = %lf\n", a);