C++程序选项选择异常:无论选何选项均触发同一结果求助
《小屁孩日记》主题C++程序逻辑错误修复
我基于《小屁孩日记》编写了一款C++程序,玩家扮演Greg的父亲,有3种处置Greg的可选操作,但运行时无论选第一个还是第三个选项,程序始终只执行第一个选项的输出逻辑。原代码如下:
#include <iostream> using namespace std; void greg(int choice){ cout<<"Option 1: Scold."<<endl; cout<<"Option 2: Take away games."<<endl; cout<<"Option 3: kill "<<endl; cin>>choice; //Options on what to do with greg and getting user input. if(choice = '1'){ cout<<"You told Greg he sucks. Responds with:"<<endl; cout<<"Ok.."<<endl; } else if(choice = '2'){ cout<<"You storm into Greg's room while Greg keeps asking you why."<<endl; cout<<"Once you are insde and grab his game."<<endl; }else if(choice = '3'){ cout<<"you killed greg."<<endl; cout<<"A white bang then proceeds to happen."<<endl; cout<<"You killed the main character. You no longer exist."<<endl; }else{ cout<<"no"<<endl; } } //All above is what will happen if you pick a choice. int main() { cout<<"There once was a guy named Frank."<<endl; cout<<"You talk to greg."<<endl; cout<<"Yeah dad?"<<endl; greg(3); return 0; }
问题根源
- 赋值/比较运算符混淆:所有
if判断里用的是=(赋值运算符),而不是==(比较运算符)。choice = '1'会把字符'1'的ASCII值(49)赋给choice,这个表达式的结果为非零,C++里会判定为true,导致第一个if分支永远触发,后面的分支根本不会执行。 - 类型不匹配:
choice是int类型,但你用字符'1'/'2'/'3'来比较,虽然能自动转换,但逻辑上不严谨。
修复后的代码
#include <iostream> using namespace std; void greg(){ int choice; cout<<"Option 1: Scold."<<endl; cout<<"Option 2: Take away games."<<endl; cout<<"Option 3: kill "<<endl; cin>>choice; //Options on what to do with greg and getting user input. if(choice == 1){ cout<<"You told Greg he sucks. Responds with:"<<endl; cout<<"Ok.."<<endl; } else if(choice == 2){ cout<<"You storm into Greg's room while Greg keeps asking you why."<<endl; cout<<"Once you are inside and grab his game."<<endl; }else if(choice == 3){ cout<<"you killed greg."<<endl; cout<<"A white bang then proceeds to happen."<<endl; cout<<"You killed the main character. You no longer exist."<<endl; }else{ cout<<"no"<<endl; } } //All above is what will happen if you pick a choice. int main() { cout<<"There once was a guy named Frank."<<endl; cout<<"You talk to greg."<<endl; cout<<"Yeah dad?"<<endl; greg(); return 0; }
修复说明
- 把所有
if条件里的=替换成==,实现正确的条件判断。 - 将比较值从字符
'1'改为整数1,和choice的int类型匹配。 - 移除
greg函数的参数choice——原参数会被输入值覆盖,完全多余,直接在函数内部定义int choice更合理。
内容的提问来源于stack exchange,提问作者popsicle7
相关产品推荐
相关产品推荐

