简体   繁体   中英

Order of operation int(4*x/y) vs int(x/(y/4))

Suppose x and y are of type int.

Are the two expressions:

int(4*x/y)

and:

int(x/(y/4))

always evaluate to the same for all x and y of type int ? They should mathematically, but only the second expression is consistent (ie, producing the expected value) in a program I've written.

In many programming languages, 4*x/y and x/(y/4) are different because y/4 , an integer, is the truncated result of the division of y by 4 . No such truncation exists in 4*x/y . On obvious difference in when y is 1 , in which case the second expression divides by zero, whereas the first one computes 4*x .

i assume x and y are ints

then of course not :) on integers: x/4=floor(x/4) mathematically

which gives you:

floor(4*x/y) and floor(x/floor(y/4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM