2016-10-20 238 views
1

我已经做了一个函数,将整数输入转换为另一个整数,它返回。具体来说,它采用控制台颜色,并返回与输入具有相同背景的对应颜色,但使用白色字符。为什么这个函数没有返回正确的值?

该函数总是返回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; 
} 

回答

4

您有多余的分号:

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

额外的分号被解析为空if声明“然后”的一部分。这有效地将您的功能分为

[ a long-winded if-else statement ] 

playerColor = 255; 

return playerColor; 
+0

哦哇,我真的很笨。谢谢。 –

1

除此之外,你有多余的分号,你可以让你的函数方法简单使用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中的值必须按排序顺序排列。

+0

谢谢,我会那样做的。 –

相关问题