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];

これで、3〜3.5randomFloatの値になります。

于 2011-11-21T22:55:23.027 に答える