首页 > 解决方案 > 我的家庭作业要求我在函数中使用布尔值。我需要将它们传递给函数吗?

问题描述

对于我的家庭作业,我应该制作一个自己的冒险故事。文本中的某些单词全部大写,代表布尔值,如果玩家得到它们,我需要在最后显示它们,例如状态效果或其他东西。我无法弄清楚如何将布尔值传递给函数,以便它到达程序的末尾,我可以在其中显示它。我的程序在函数中有函数。

我已经尝试使将布尔值设置为 true 的函数本身成为布尔值,然后返回布尔值,但这似乎只是结束了程序。我还尝试通过第一个函数调用传递它以查看它是否到达第二个,但它似乎并不想要。

void A1();
bool A100(bool INTIM);
void A167();
void A232();
void A290();
void A13();
void A212();
void A173();
void A159();
void A161();

int main() {
bool INTIM;

A1();
cout << INTIM << endl;
return 0;
}
void A1()
{
  int choice;
  cout << "Well, Mr Artanon, ...\n 1. ’It’s you who’ll get a rare cut 
across that corpulent neck of yours if you don’t speed things along, you 
feckless blob of festering lard.’\n 2. ’Surely in such an industrious 
kitchen, there must be a starter or two ready to send along and sate His 
Abhorentness’s appetite?’\n (enter a menu option): ";
  cin >> choice;

  while (choice != 1 && choice != 2)
  {
    cout << "Enter in a valid choice (1 or 2)";
    cin >> choice;
  }

  if (choice == 1)
  {
    A100();
  }

  if (choice == 2)
  {
    A167();
  }
}

bool A100(bool INTIM)
{
  int choice;
  INTIM = true;
  cout << " Repugnis turns a paler...\n 1. Onwards, Mr Artanon.\n (enter 
in a menu option): ";
  cin >> choice;

  while (choice != 1)
  {
    cout << "Enter in a valid option (1)";
  }
  return INTIM;
  A232();
  }

我想要发生的是,要传递的 bool INTIM 以便我可以使用 cout 语句将其显示回 main 中。我知道它最后只会是 1 或 0,但我只是想让它至少在最后显示时显示出来。同样,该程序中的函数中有函数,这可能是我的问题,但我不这么认为。在此之后还有一些功能,这不是程序的结束,如果我需要发布整个内容,我会

标签: c++functionboolean

解决方案


写的调用A100,需要传入INTIM并接受返回值

INTIM = A100(INTIM);

但是......INTIM从未使用过的初始状态,所以你可以

INTIM = A100();

并改变A100看起来更像

bool A100()
{
  int choice;
  cout << " Repugnis turns a paler...\n 1. Onwards, Mr Artanon.\n (enter in a menu option): ";
  cin >> choice;

  while (choice != 1)
  {
    cout << "Enter in a valid option (1)";
    cin >> choice; // added here because otherwise choice never changes
                   // and this loop will go on for a long, long time.
  }
  A232(); // moved ahead of return. Code after a return is not run
  return true;
}

但是由于A232被调用并且可能会设置您无法返回的附加标志,因此您有一个设计缺陷:如果A232还修改了布尔值怎么办?您只能从函数返回一件事。您可以通过A232引用传递 ' 布尔值,但是它A232随后调用什么B484并且它也有一个布尔值?

您不想传递所有可能的布尔值,这会造成混乱,因此请考虑创建一个存储所有布尔值的数据结构以进行传递。

这导致了一个更好的想法:将布尔值和函数封装在同一个数据结构中,这样您就不必传递任何东西;都在同一个地方。


推荐阅读