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.
I believe I could do this using some sort of if statement, but this would mean many more lines of code. 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?. 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?
float valueCalculated = ((val1 / val2) * 100) % 101;
?
如果只想通过“加权”将计算的值限制为0到100,则可以将该值除以可能的最大值,然后乘以100。这假定该值不是负数。
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.