为什么这个函数没有返回正确的值?

Why is this function not returning the correct value?

本文关键字:返回 函数 为什么      更新时间:2023-10-16

我编写了一个函数,将输入的整数转换为返回的整数。具体来说,它接受一个控制台颜色,并返回一个与输入具有相同背景的相应颜色,但带有一个白色字符。

这个函数总是返回255。出了什么问题?

int convertColorToPlayerColor(int color)
{
    int playerColor = 0;
    if (color <= 15)
        playerColor = 15;
    else if ((color > 15) && (color <= 31))
        playerColor = 31;
    else if ((color > 31) && (color <= 47))
        playerColor = 47;
    else if ((color > 47) && (color <= 63))
        playerColor = 63;
    else if ((color > 63) && (color <= 79))
        playerColor = 79;
    else if ((color > 79) && (color <= 95))
        playerColor = 95;
    else if ((color > 95) && (color <= 111))
        playerColor = 111;
    else if ((color > 111) && (color <= 127))
        playerColor = 127;
    else if ((color > 127) && (color <= 143))
        playerColor = 159;
    else if ((color > 159) && (color <= 175))
        playerColor = 175;
    else if ((color > 175) && (color <= 191))
        playerColor = 191;
    else if ((color > 191) && (color <= 207))
        playerColor = 207;
    else if ((color > 207) && (color <= 223))
        playerColor = 223;
    else if ((color > 223) && (color <= 239))
        playerColor = 239;
    else if (color > 239);
        playerColor = 255;
    return playerColor;
}

你有一个额外的分号:

else if (color > 239);    // <--- the semicolon

额外的分号被解析为空if语句的"then"部分。这有效地将函数转换为

[ a long-winded if-else statement ]
playerColor = 255;
return playerColor;

除了你有额外的分号,你可以使你的功能方式更简单使用returnif和删除冗余检查:

   if (color <= 15)
      return 15;
   if (color <= 31) // no need to check color > 15
      return 31;
   if (color <= 47) // no need to check color > 31
      return 47;
   ...
   return 255; // no need for if (color > 239) 

你也可以做二进制查找而不是线性检查:

int convertColorToPlayerColor(int color)
{
     static std::vector<int> v { 15, 31, 47, 63, 79, 95, 111, 127, 143, 175, 191, 207, 223, 239 };
     auto it = std::lower_bound( v.begin(), v.end(), color );
     return it == v.end() ? 255 : *it;
}

不仅使它更有效、更短,而且使它更不容易出错(因为您不必重复数字多次)。请记住,vector中的值必须按顺序排序。