1

我有以下测试用例

#include <stdio.h>

int main() { 

    double x = 3.987;

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

    printf("(double) (long) (x) = %lf\n", (double) (long) (x));

    printf("(x*100)/100 = %lf\n", (x*100)/100);

    printf("(double) (long) (x*100)/100 = %lf\n", (double) (long) (x*100)/100);

    printf("(double) (long) (x*10)/10 = %lf\n", (double) (long) (x*10)/10);

    return 0;
}

输出是:

x = 3.987000
(double) (long) (x) = 3.000000
(x*100)/100 = 3.987000
(double) (long) (x*100)/100 = 3.980000
(double) (long) (x*10)/10 = 3.900000

在我看来,乘以 100 除以 100 会相互抵消吗?但它实际上是在降低精度。这究竟是如何工作的?

4

2 回答 2

5

在某些地方,您要转换为“long”,它是一个整数类型。例如,在最后一种情况下,您将 3.987 乘以 10,得到 39.87。然后,您将其转换为“long”,使其变为 39。除以 10 后,您得到 3.9。

你想通过使用来实现(long)什么?

于 2013-10-13T20:53:36.757 回答
0

类型转换为long比除以 100 具有更高的优先级。所以

(double) (long) (x*100)/100

实际上相当于

((double) (long) (x*100)) / 100

(double) (long) ((x*100)/100)
于 2013-10-13T20:54:54.547 回答