这个if-else声明能否变得更加清晰

B S*_*ith 8 c++

我正在尝试改进C++分配以使其更有效.我是语言的初学者(也是一般的编程),所以我只使用我目前所知的(如果,其他).我有一个将分数转换为等级的功能,因此任何低于30 = 1,30-49 = 2,50-79 = 3等等......

我是这样做的:

if (score1 <= 30) level1 = 1;
else if (score1 <= 49) level1 = 2;
else level1 = 3;

if (score2 <= 30) level2 = 1;
else if (score2 <= 49) level2 = 2;
else level2 = 3;

//etc...
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点,因为我知道这将需要我的每一个分数的新线.

The*_*aul 13

这取决于你的效率意味着什么.您可以保持数组中每个级别的限制

int level_limits[] = {0, 30, 49, 79, [...]};

int getLevel(int score)
{
   int level;
   for (level = 0; level < N_LEVELS; ++level)
       if (level_limits[level] > score)
            return level;
   return level; // or whatever should happen when you exceed the score of the top level
 }
 ...

 level1 = getLevel(score1);
 level2 = getLevel(score2);
Run Code Online (Sandbox Code Playgroud)

... 或类似的东西.

  • `l + = 1`在C++中拼写为`++ l`. (5认同)
  • 我不建议使用l作为变量名,因为它很容易与1混淆(我实际上做了=)). (2认同)

phk*_*ler 5

创建一个传递得分的函数,它返回级别.此外,如果有很多,你应该创建一个分数和级别的数组.

for (x=0;x < num_scores;x++)
{
   level[x] = get_level(score[x]);
}
Run Code Online (Sandbox Code Playgroud)

类似的东西.

  • 为什么使用`x!= num_scores`而不是`x <num_scores`? (4认同)

vit*_*aut 5

首先将用于计算级别的代码分解为单独的函数,比如get_level:

level1 = get_level(score1);
level2 = get_level(score2);
Run Code Online (Sandbox Code Playgroud)

您可以通过不同方式实现get_level.

如果级别数量很小,您可以使用线性搜索:

const int bounds[] = {30, 49, 79}; // Add more level bounds here.

int get_level(int score)
{
    const size_t NUM_BOUNDS = sizeof(bounds) / sizeof(*bounds);
    for (size_t i = 0; i < NUM_BOUNDS; ++i)
        if (score <= bounds[i])
            return i + 1;
    return NUM_BOUNDS + 1;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您是STL粉丝:

#include <algorithm>
#include <functional>

const int bounds[] = {30, 49, 79}; // Add more level bounds here.

int get_level(int score)
{
    return std::find_if(bounds,
        bounds + sizeof(bounds) / sizeof(*bounds),
        std::bind2nd(std::greater_equal<int>(), score)) - bounds + 1;
}
Run Code Online (Sandbox Code Playgroud)

如果你有很多级别二分搜索可能更合适:

#include <algorithm>

const int bounds[] = {30, 49, 79}; // Add more level bounds here.

int get_level(int score)
{
    return std::lower_bound(bounds,
        bounds + sizeof(bounds) / sizeof(*bounds), score) - bounds + 1;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您的级别相对较少,则使用与原始版本类似的if-else链:

int get_level(int score)
{
    if (score <= 30)
        return 1;
    else if (score <= 49)
        return 2;
    else if (score <= 79)
        return 3;
    return 4;
}
Run Code Online (Sandbox Code Playgroud)

请注意,将返回放在单独的行上可以使您的程序更容易在调试器中进行跟踪.