round(((27 + 28 + 28)/ 3)返回27 ?! (C / C ++)

我的代码(使用C语言)是这样的:

avg = round(r + g + b) / 3);

r = avg;
g = avg;
b = avg;

It should do the grayscale image effect. There are no syntax errors, but apperently avg, when calculated as shown above with values r as 27, and both g and b as 28, avg finds it to be 27. I know it is 27.66666... and when rounded that is 28. if you can either-or/both explain to me why this happens with round(), and/or give me a solution, it is really appreciated. thanks!

评论
骑青旋
骑青旋

Assuming that r, g, and b have integer types, the expression (r + g + b) / 3 performs integer division because all operands have integer type. This means that any fractional part of the division gets truncated.

将表达式更改为此:

(r + g + b) / 3.0

The constant 3.0 has type double, so this will perform floating point division. Then rounding the result of this expression will give you the desired result.

点赞
评论