简体   繁体   English

修剪十分之一的数字的算法

[英]Algorithm to trim tenths hundredths thousandths numbers

I need to detect which word I need to display that is correspond to the user score. 我需要检测要显示的与用户得分相对应的单词。

I have next switch: 我有下一个开关:

switch (score) {
        case 0:
            outString = @"String1";
            break;
        case 1:
            outString = @"String2";
            break;
        case 2:
            outString = @"String3";
            break;
        case 3:
            outString = @"String3";
            break;
        case 4:
            outString = @"String3";
            break;
        case 5:
            outString = @"String1";
            break;
        case 6:
            outString = @"String1";
            break;
        case 7:
            outString = @"String1";
            break;
        case 8:
            outString = @"String1";
            break;
        case 9:
            outString = @"String1";
            break;           

        default:
            break;
    }

But, how I can use the same switch when score will be 29 or 109. So I need to trim in the first case 20 to get 9 and in the second case I need to trim 100 to get 9. 但是,当得分为29或109时如何使用相同的开关。因此,我需要在第一种情况下将20修剪为9,在第二种情况下,需要将100修剪为9。

I used this algorithm before, but I forgot how to :( 我以前使用过这种算法,但是我忘了如何:(

So the goals is next - I every time need just number from 0 - 9 without tenths hundredths thousandths numbers. 所以目标是下一个-我每次只需要0到9之间的数字,而不用千分之一的数字。

If your word always depends on last digit of number, you can simply use it in switch condition (using modulus operator): 如果您的单词始终取决于数字的最后一位数字,则可以简单地在切换条件下使用它(使用模运算符):

switch (score % 10)
   ...

If only 29 and 129 are special cases then you can use multiple labels for the same case: 如果只有29和129是特殊情况,则可以在同一情况下使用多个标签:

case 9:
case 29:
case 109:
        outString = @"String1";
        break;

Much better than to use a giant switch statement, is to use a lookup table: 使用查找表比使用巨型switch语句要好得多:

std::string score_string(unsigned int score)
{
    static const std::string strings = {"String1","String2","String3",...};
    static const int strings_count = 10; //10 strings in the lookup table, for example.

    return strings[score % strings_count];
}

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

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