为什么这个函数没有返回正确的值?
Why is this function not returning the correct value?
我编写了一个函数,将输入的整数转换为返回的整数。具体来说,它接受一个控制台颜色,并返回一个与输入具有相同背景的相应颜色,但带有一个白色字符。
这个函数总是返回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;
除了你有额外的分号,你可以使你的功能方式更简单使用return
在if
和删除冗余检查:
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中的值必须按顺序排序。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数