所以基本上我要做的就是把这段代码转换成一个switch语句。我真的不知道该怎么做。我有几个想法,比如用关键字做一个有值范围的枚举(例如"enum hare { ONE =(range from 1-5) TWO = (range from 6-8)} -但我不知道这是不是一个错误:S
希望我已经清楚了我想问的问题。
int y = 1 + rand() % 10;
// determine which move to make
if ( y == 1 || y == 2 ) {
hare += 0;
} else if ( y == 3 || y == 4 ) {
hare += 9;
} else if (y == 5) {
hare -= 12;
} else if (y >= 6 && y <= 8){
hare += 1;
} else if (y == 9 || y == 10){
hare -= 2;
}else {
++( hare );
}
if ( hare < 1 ) {
hare = 1;
} else if ( hare > RACE_END ) {
hare = RACE_END;
}发布于 2014-03-17 11:30:32
第一个问题是,进行转换是否有真正的价值。那么对于这种情况,操作实际上很简单,因为在除else之外的所有情况下,都有少量有效的情况:
switch (y) {
case 1: case 2:
break;
case 3: case 4:
hare += 9;
break;
case 5:
hare -= 12;
break;
case 6: case 7: case 8:
hare += 1;
break;
case 9: case 10:
hare -= 2;
break;
default:
++hare;
}发布于 2014-03-17 11:31:10
如果您想使用switch语句,可以这样做
switch( y ){
case 1:
case 2: hare += 0; break;
case 3:
case 4: hare += 9; break;
case 5: hare -= 12; break
case 6:
case 7:
case 8: hare += 1; break;
case 9:
case 10: hare -= 2; break;
default: ++(hare);
}但是,使用enum,enum hare { ONE =(range from 1-5) TWO = (range from 6-8)}是...您正在尝试将多个值存储在one variable中,这是不可能的。
switch语句的Reference
发布于 2014-03-17 11:31:19
你可以很容易地做这样的事情:
switch(y)
{
case 1:
case 2:
//do something
break;
default:
//
}因此,根据y的值,您的情况会有所不同。
https://stackoverflow.com/questions/22446368
复制相似问题