简体   繁体   中英

Do Math.max and Math.min change the value they are applied to?

I've been reading some code that one of my lecturers set and he has written something like "Let us set a maximum and minimum for a value."

Then he writes (and I'm paraphrasing values here)

int x = 5;
x = Math.min(x, 0);
x = Math.max(x, 10);

Then he carries on with his code as if x is still equal to 5 whereas when I run this code through my computer the max and min functions always change the value of x to 0 and then 10.

Does this sound like a mistake on his part? Should he have reverted x before carrying on? Or does this function work in some other way depending on circumstances that it does actually set a maximum and minimum value without changing the original variable?

You are right; he probably meant this:

int x = 5;
x = Math.max(x, 0);
x = Math.min(x, 10);

which keeps x between 0 and 10.

It is a mistake on his part. When you assign a variable with = it sets it to that value.

Yes. It is a mistake on his part.

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