Dividing by two integers does not return expected result

前端 未结 6 664
甜味超标
甜味超标 2021-01-25 13:18

I\'m currently writing a program that requires a preview of a live display, but the preview, of course, is scaled down. However, when I scale the PictureBox down, t

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-25 13:18

    C#'s math is "correct". The understanding of what is being done is .. missing :-)

    The expression 4 / 3 (of type int / int) will evaluate to the integer value 1 as it is using integer division (both operands are integers). The resulting 1 is then implicitly coerced to a double value on assignment.

    On the other hand 4d / 3 will "work" (and results in a double 1.333_) because now it is double / int -> double / double (by promotion) -> double using the appropriate floating point division.

    Similarly, for Height / 4 (assuming Height is an integer), these would work:

    (double)Height / 4          // double / int -> double
    Height / 4d                 // int / double -> double
    (double)Height / (double)4  // double / double -> double
    

    Happy coding!

提交回复
热议问题