gpt4 book ai didi

c++ - if 和 if-else 语句不适用于 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:20:40 24 4
gpt4 key购买 nike

所以我和我的 friend 正在尝试制作一个基于文本的视频游戏,并且我一直在研究如何降低编程的难度。到目前为止,这是我们的 C++ 程序:

#include <iostream>
#include <stdio.h>

char Choice;

using namespace std;

int main()
{
printf("You wake up to darkness.\n");
printf("Confused and tired, you walk to the nearest house.\n");
printf("You notice it's abandoned. What do you do?\n");
printf("1. Walk Away.\n");
printf("2. Jump.\n");
printf("3. Open Door.\n");
printf("Choose wisely.\n");
cin >> Choice;

if(Choice=1)
{
printf("The House seems to have a gravital pull on you. How strange.\n");
}

else if(Choice=2)
{
printf("Having Fun?\n");
}

return 0;
}

但是当我构建并运行时,它会显示所有内容,但所有答案都将是 if(Choice=1) 答案。我的程序中是否缺少某些需要的东西或部分是否相互矛盾?

最佳答案

您需要比较运算符 ==,而不是赋值运算符 =。这些是不同的运算符。使用 = 会改变 Choice 的值,这不是你想要的。 (您的编译器应该警告您在 if 语句中使用 =。)

1 是整数 1。您要检查字符 '1'(ASCII 值 49),这是不同的。使用 '1' 而不是 1

if (Choice == '1')
{
printf("The House seems to have a gravital pull on you. How strange.\n");
}
else if (Choice == '2')
{
printf("Having Fun?\n");
}

此外,您正在混合使用两种类型的 I/O。使用 cin 作为输入很好。您应该使用其对应的 cout 进行输出,而不是 printf

cout << "You wake up to darkness." << endl;
cout << "Confused and tired, you walk to the nearest house." << endl;

关于c++ - if 和 if-else 语句不适用于 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com