我对编程领域还比较陌生。我尝试过几种语言,但最终决定从 C 开始,因为它提供支持并且易于入门。我目前正在尝试编写一个简单的基于文本的征服类游戏。 有了这个,就有大量的地方或领土可供选择攻击,等等。我给每个区域一个数字 ID 1-50,这就是我的问题所在。我能想到的测试用户输入的 ID 的唯一方法是编写 50 个 if 语句,这是 super 乏味且烦人的。有更简单的方法吗?
AttackTrue(){
int AmountOfTroops;
int TerrToAttack;
//List of territories with their id
// example: int California = 1;
printf("You have %d troops\n");
printf("Enter the number of troops you want to use.");
scanf(" %d",&AmountOfInfantry);
printf("Enter the ID of the territory you want to attack.\n");
scanf(" %d",&TerrToAttack);
/*HERE IS WHERE ALL THE IF STATEMENTS WOULD GO*/
}
}
最佳答案
您可以按照 JerryGoyal 的建议使用 switch case。 另一种方法是使用指向函数的指针数组:
void* (*funcLUT[50])(void*);
创建一个init函数来填充数组(最好有一个DoNothing()函数作为默认值)并根据ID调用该函数:
retValue = funcLUT[ID](data);
希望有帮助
关于C 如何减少 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687358/