在 c 中评估表达式以便用双精度值写入

evaluating expression in c in order the are written with doubles

我正在做一道家庭作业题,除了这道题,我什么都能做。我想我知道如何去做,我只是想确定一下。

Assume the following declarations:

int a =1, b = 2, c = 3;

Fully parenthesize and evaluate each of the following expressions assuming they are evaluated in the order in which they are written.

所以我有 2 个表达式:

(double)a / b * c

a / (double)(b + c)

我用括号括起来

((double)a) / (b * c)

(a) / ((double)(b + c))

我只是不确定如何解决问题的双重部分,这是否意味着它的评估将以 3.000 或 5.000 这样的方式打印,而不是像常规的那样int 例如 3 或 5?

I am just not sure on how to go about solving the double part of the question, does this just mean that it the evaluation of this will be printed in such a fashion of like 3.000 or 5.000 not just like a regular int such as 3 or 5?

表示转换为double。打印是一个完全不同的(并且在这里是不相关的)问题。您将拥有一个具有允许浮点值的内部表示的临时文件。顺便说一句,这将强制同一表达式中的所有其他 int 也转换为 double

(double)a/b * c
[...]
((double)a)/(b*c)

这是错误的。 /* 具有相同的优先顺序......所以,按照书面的方式进行评估,应该是 (((double)a)/b)*c.

我想你只需要了解任何时候整数类型和浮点类型之间的运算,整数类型被提升为浮点类型所以...

示例 1:

(double)a/b * c
>>> 1.0/2*3 = (0.5) * 3 = 1.5

这与非强制转换版本不同,整数除法会舍弃余数,您最终会得到 0...1/2*3 -> 0 * 3 -> 3

示例 2:

a/(double)(b+c)
>>> 1/ (double) (2+3) = 1/(5.0) = .20

因此,当您将这些值分配给浮点数或双精度数时,它们将是那些值,如果将它们分配给整数类型,它们将分别为 1 和 0,因为它会丢弃余数...

关于强制转换适用于哪一部分(我认为这是你问题的一部分)...C 中有一套非常固定的操作顺序,请参阅 (operator precedence in c)...您将看到强制转换的优先级高于除法...否则...

(double)1/2 * 3 -> (double)(1/2) * 3
>>> 0.0 * 3 = 0.0