为什么 double 变量在 c 中除法后不显示余数?

Why double variable is not showing remainder after division in c?

我一定犯了一些严重的错误,但我正在用 C 计算 2880 * 12 / 512 的结果,即使我将结果保存在 double 变量中,它只是不保存其余部分。根据 Google 和任何其他计算器 2880 * 12 / 512 = 67.5 然而根据下面的程序它是 67.00。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>

int main() {
    double result;
    result = 2880 * 12 / 512;
    printf("result = %f\n", result);
    return 0;
}

我正在编译名为 test.c 的文件,其中包含如下代码:gcc test.c -o test -lm

我做错了什么?

键入您的整数文字值。像这样。

result = (double)2880 * 12 / 512;

C11 标准:

6.5.5 Multiplicative operators

6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

2880 * 12 / 512 都是整数表达式,计算结果为整数。事实上,它被分配给一个双精度变量,但精度会丢失。您需要转换为双精度,以便计算结果为双精度。

result = (double)2880 * 12 / 512;

或者附加一个小数点来告诉编译器它是一个浮点数:

result = 2880. * 12 / 512;