Ios 编写if语句的最干净方法

Ios 编写if语句的最干净方法,ios,if-statement,Ios,If Statement,我有一个if声明,我认为它不干净,写得不好。我有一个值,可以根据该值减小和更改节点的比例。因此,如果值为95,则刻度为0.95 写这篇文章最好的方法是什么?我一直在绞尽脑汁想最好的办法 我现在正在做 //Set Stamina if(hungerInt >= 100){ _foodNode.scaleY = 1.0f; } else if (hungerInt >=95){ _foodNode.scaleY = 0.95f; } else if (hunger

我有一个if声明,我认为它不干净,写得不好。我有一个值,可以根据该值减小和更改节点的比例。因此,如果值为95,则刻度为0.95

写这篇文章最好的方法是什么?我一直在绞尽脑汁想最好的办法

我现在正在做

//Set Stamina
if(hungerInt >= 100){

    _foodNode.scaleY = 1.0f;

} else if (hungerInt >=95){

    _foodNode.scaleY = 0.95f;

} else if (hungerInt >=90){

    _foodNode.scaleY = 0.90f;

} else if (hungerInt >=80){

    _foodNode.scaleY = 0.80f;

} else if (hungerInt >=70){

    _foodNode.scaleY = 0.70f;

} else if (hungerInt >=60){

    _foodNode.scaleY = 0.60f;

} else if (hungerInt >=50){

    _foodNode.scaleY = 0.50f;

} else if (hungerInt >=40){

    _foodNode.scaleY = 0.40f;

} else if (hungerInt >=30){

    _foodNode.scaleY = 0.30f;

} else if (hungerInt >=20){

    _foodNode.scaleY = 0.20f;

} else if (hungerInt >=10){

    _foodNode.scaleY = 0.10f;

} else {

    _foodNode.scaleY = 0.0f;

}

理想情况下,我希望它根据值进行精确缩放,因此如果它是
96
,它将是0
96
,或者如果它是
51
,它将是
0.51
,否
,如果需要:

_foodNode.scaleY = (CGFloat)hungerInt / 100.0f;
虽然这仅在您可以保证hungerInt
介于
0
100
之间时有效,但您可能需要先检查该值

if (hungerInt < 0)
    hungerInt = 0;
else if (hungerInt > 100)
    hungerInt = 100;
if(饥饿<0)
饥饿指数=0;
否则,如果(饥饿>100)
饥饿指数=100;

为什么不能直接使用

_foodNode.scaleY = hungerInt / 100.0f;

如果您不希望
\u foodNode.scaleY
超过1.0并低于0.0,则可以使用此代码

_foodNode.scaleY = MAX( 0, MIN( (CGFloat)hungerInt / 100.0, 0 ) );
或者你可以用一个函数来做

// some pseudo c code. 
static CGFloat minMax(CGFloat n) {
    return MAX(0, min(100, n));
}
然后这样称呼它:

_foodNode.scaleY = minMax((CGFloat)hungerInt) / 100.0