简体   繁体   English

Math.max和Math.min会更改它们应用的值吗?

[英]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. 然后,他继续执行自己的代码,好像x仍等于5,而当我通过计算机运行此代码时,max和min函数始终将x的值更改为0,然后更改为10。

Does this sound like a mistake on his part? 这听起来像他的错误吗? Should he have reverted x before carrying on? 他应该在继续之前恢复x吗? 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. 将x保持在0到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. 这是他的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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