1

我有这个方法:

- (float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2 {
return ((float)arc4random() / ARC4RANDOM_MAX) * num2-num1 + num1;
}

我很好奇,如果有可能而不是使用以下条件:我想为我的游戏做一个随机浮动,如下所示:

When the score is:
Score 0-20: I want a float between 4.0-4.5 using the above method
Score 21-40: I want a float between 3.0-3.5 using the above method
Score 41-60: I want a float between 2.5-3.0 using the above method
Score 61+: I want a float between 2.0-2.5 using the above method

现在我知道我可以使用条件来做到这一点,但是有没有比这样做更容易的数学方程式?

谢谢!

编辑1:

    - (float)determineFloat {
    if (score <= 60)
    {
        //Gets the tens place digit, asserting >= 0.
        int f = fmax(floor( (score - 1) / 10 ), 0);

        switch (f)
        {
            case 0:
            case 1:
            {
                // return float between 4.0 and 4.5
                [self randomFloatBetween:4.0 andLargerFloat:4.5];
            }
            case 2:
            case 3:
            {
                // return float between 3.0 and 3.5
                [self randomFloatBetween:3 andLargerFloat:3.5];
            }
            case 4:
            case 5:
            {
                // return float between 2.5 and 3.0
                [self randomFloatBetween:2.5 andLargerFloat:3];
            }
            default:
            {
                return 0;
            }
        }
    }
    else
    {
        // return float between 2.0 and 2.5
        [self randomFloatBetween:2.0 andLargerFloat:2.5];
    }
    return;
}

这个怎么样?。您还确定这是最有效的方法吗?

4

1 回答 1

2

可能不是,因为这种关系不是连续的。当您有这种要求时,最好只使用条件或 switch 语句。你和任何阅读或调试代码的人都会知道函数在做什么。在这种情况下使用某种数学函数,这将是极其复杂的,充其量是很可能会减慢这个过程。

使用开关的可能性:

-(float)determineFloat:(float)score
{
    if (score <= 60)
    {
        //Gets the tens place digit, asserting >= 0.
        int f = (int)fmax(floor( (score - 1) / 10.0f ), 0);

        switch (f)
        {
            case 0:
            case 1:
            {
                return [self randomFloatBetween:4.0 andLargerFloat:4.5];
            }
            case 2:
            case 3:
            {
                return [self randomFloatBetween:3.0 andLargerFloat:3.5];
            }
            case 4:
            case 5:
            {
                return [self randomFloatBetween:2.5 andLargerFloat:3.0];
            }
            default:
            {
                return 0;
            }
        }
    }
    else
    {
        return [self randomFloatBetween:2.0 andLargerFloat:2.5];
    }
}

用法:

float myScore = 33;
float randomFloat = [self determineFloat:myScore];

现在,randomFloat将是一个介于 3 和 3.5 之间的值。

于 2011-11-21T22:55:23.027 回答