在C ++中使用非常长的if else if语句的替代方法

时间:2014-09-15 18:57:48

标签: c++

我目前正在编写一种算法来为程序生成项目生成类似地图的岛屿。我的显示代码的一部分采用浮动高度(介于0和1之间的值)并将其钳制到特定的0.05值,以便生成轮廓而不是高度的连续变化。

这是我非常长的if else声明:

float newHeight;

if (height > 0.0 && height <= 0.05) {
    newHeight = 0.05;
} else if (height > 0.05 && height <= 0.1){
    newHeight = 0.1;
} else if (height > 0.1 && height <= 0.15){
    newHeight = 0.15;
} else if (height > 0.15 && height <= 0.2){
    newHeight = 0.2;
} else if (height > 0.2 && height <= 0.25) {
    newHeight = 0.25;
} else if (height > 0.25 && height <= 0.3) {
    newHeight = 0.3;
} else if (height > 0.3 && height <= 0.35) {
    newHeight = 0.35;
} else if (height > 0.35 && height <= 0.4) {
    newHeight = 0.4;
} else if (height > 0.4 && height <= 0.45) {
    newHeight = 0.45;
} else if (height > 0.45 && height <= 0.5) {
    newHeight = 0.5;
} else if (height > 0.5 && height <= 0.55){
    newHeight = 0.55;
} else if (height > 0.55 && height <= 0.6){
    newHeight = 0.6;
} else if (height > 0.6 && height <= 0.65){
    newHeight = 0.65;
} else if (height > 0.65 && height <= 0.7){
    newHeight = 0.7;
} else if (height > 0.7 && height <= 0.75){
    newHeight = 0.75;
} else if (height > 0.75 && height <= 0.8){
    newHeight = 0.8;
} else if (height > 0.8 && height <= 0.85){
    newHeight = 0.85;
} else if (height > 0.85 && height <= 0.9){
    newHeight = 0.9;
} else if (height > 0.9 && height <= 0.95){
    newHeight = 0.95;
} else if (height > 0.95) {
    newHeight = 1.0;
} else {
    newHeight = 0.0;
}

它作为迭代高度值数组的函数的一部分运行。我对C ++和编程很新,但到目前为止还没有能够在stackoverflow上找到任何与此特定问题有关的内容。必须有一个更好的方法来做到这一点,因为增加额外的“轮廓”将是真正不可行的。

任何输入都将非常感谢!感谢。

1 个答案:

答案 0 :(得分:0)

您可能想要查看查找表:

+-------+-------+-------+  
| lower | upper |  new  |  
| bound | bound |height |  
+-------+-------+-------+  

你制作了这些数组。
如果height在范围内,则使用同一条目中的new height

if ((height > table[i].lower_bound) && (height <= table[i].upper_bound))
{
  height = table[i].new_height;
  break; // out of loop.
}