简体   繁体   English

设置价值限制,iPhone

[英]Set Limit For Value, iPhone

I have the following code: 我有以下代码:

float valueCalculated = (val1 / val2) * 100;

What I want to be able to do is to cap the maximum value of valueCalculated to 100. 我想要做的是将valueCalculated的最大值限制为100。

I believe I could do this using some sort of if statement, but this would mean many more lines of code. 我相信我可以使用某种if语句来做到这一点,但这将意味着更多的代码行。 Edit// This is not the case, see the answers below. 编辑//并非如此,请参见下面的答案。

Thanks, 谢谢,

Stu 斯图

您是说这样的“多行代码”?

if (valueCalculated > 100) { valueCalculated = 100; }
float valueCalculated = MIN((val1 / val2) * 100, 100);
float valueCalculated = (float temp = (val1 / val2) * 100) > 100 ? 100 : temp;

but I guess a function would be better, you can do with function or a simple macro: 但是我想函数会更好,您可以使用函数或简单的宏:

#define MAX(m, toset) toset = (toset > m ? m : toset)

MAX(100, valueCalculated);

I guess I understood better your question: 我想我对您的问题了解得更好:

valueCalculated = MAX(100, (val1 / val2) * 100);

where 哪里

#define MAX(max, val) (((val) > (max)) ? (max) : (val))

hope it helps, 希望能帮助到你,
Joe

If I understand the question then... 如果我理解这个问题,那么...

float valueCalculated = fminf((val1 / val2) * 100, 100);

...should do what your asking. ...应该按照您的要求做。

However, are you worried about negative values, ie could val1 or val2 be negative and do you want to limit possible values for valueCalculated to 0-100?. 但是,您是否担心负值,即val1或val2是否为负,您是否想将valueCalculated的可能值限制为0-100? If so then you might want... 如果是这样,那么您可能想要...

float valueCalculated = fmaxf(fminf((val1 / val2) * 100, 100), 0);

那这个呢:

float valueCalculated = ((val1 / val2) * 100 < 100) ? (val1 / val2) * 100 : 100

I'm not an iphone dev, but isn't modulo what you're looking for? 我不是iPhone开发人员,但不是要寻找所需的模数吗?

float valueCalculated = ((val1 / val2) * 100) % 101;

?

如果只想通过“加权”将计算的值限制为0到100,则可以将该值除以可能的最大值,然后乘以100。这假定该值不是负数。

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

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