我正在处理这个C++代码,但无法让它工作......见下文

I working on this C++ code and can't get it to work...see below

本文关键字:工作 下文 处理 代码 C++      更新时间:2023-10-16

无法让它工作...路障。。。。帮助?!? 我是新手,正在尝试为Delco CC的C++课程编写游戏代码。 任何帮助将不胜感激。 当它运行时,它不会按预期循环,因此我无法继续编写游戏的其余部分。

#include<iostream>
#include<string>
using namespace std;
int findMap()
{
int space;
cout<<"|  1  |  2  |  3  |"<<endl;
cout<<"|_____|_____|_____|"<<endl;
cout<<"|  4  |  5  |  6  |"<<endl;
cout<<"|_____|_____|_____|"<<endl;
cout<<"|  7  |  8  |  9  |"<<endl;
cout<<"|     |     |     |"<<endl;
cout<<"What space is your map in?"<<endl;
cin>> space;
if (space == 4||8)
{
          cout<<"Nope! There's nothing in here."<<endl;
          return findMap;
          }
if (space == 5||6)
{
          cout<<"Tough luck, you only found blank map paper. It's
useless."<<endl
          return findMap;
          }
if (space == 1||7)
{
          cout<<"You found poision gas. You failed."<<endl;
          return 0;
          }
if (space == 1)
{
          cout<<"Yippie! You found your map!"<<endl;
          }
if (space == 9)
{
          cout<<"Well, you found your wallet..."<<endl;
          return findMap;
          }

}
int game(findMap)
{
string name;
int findMap;
cout<<"It appears that you have been lost at sea."<<endl;
cout<<"But don't worry, you'll only have to survive until you reach
land, for this round."<<endl;
cout<<"Anyways, why don't you tell me your name?"<<endl;
cin>> name;
cout<<"Well, "<< name<<", do yourself a favour and find your
map..."<<endl;
cout<<findMap<<endl;
}

这样的经典缺陷错别字

逻辑 OR 指定为:

if ((space == 1) || (space ==7))

这与评估语义的顺序有关。

编辑 1:为什么您的版本无法正常工作
在表达式中:

 (space == 1 || 7)

短语1||7首先被评估为真实条件。
现在的表达式是:

  (space == true)

标识符true的类型为 bool,因此它被转换为与 space 相同的类型,即 inttrueint表示形式是 1
替换给我们:

(space == 1)

你很幸运,但7的情况并不存在。 所有 if 语句的计算方式都相同。

这是 c++ 中常见的误解。或(||(运算符通常用于布尔值。因此,当您检查(space == 1||7)时,它首先计算space == 1当且仅当空间等于 1 时计算结果为 true。然后在它计算(space == 1)后,它将 or 运算符应用于 7。由于 7 的计算结果始终为 true,(space == 1||7) 始终计算为 true,因为如果表达式中的任何部分的计算结果为 true,则 or 运算符的计算结果为 true。

你想要的是(space == 1 || space == 7)因为它将计算第一个,然后是第二个子表达式(即 space == 1 ,则 space == 7 ( 并返回 true,当且仅当其中任何一个计算结果为 true。