【问题标题】:99 Bottles of beer on the wall using boolean method [closed]99瓶啤酒在墙上使用布尔方法[关闭]
【发布时间】:2021-04-27 12:50:45
【问题描述】:

你好,我正在尝试从这个 bool 方法中提取这个 cout 对话框。我希望能够输入瓶子的初始数量,然后调用布尔方法来确定它是否在范围内。如果为真,它将返回布尔方法中的对话,如果不是,它将要求用户再次输入金额。以下是我到目前为止的内容,但我非常困惑。

bool bottleAmount(int amount); // function prototype

int main()

{
int amount = 0;
cout << "How many bottles of beer on the wall? ";
cin >> amount;

bottleAmount(amount);
return 0; 

}

       bool bottleAmount(int amount)
{
bool status;

if (amount >= 2)
    status = true;
{
    for (amount; amount > 0 && amount < 101; amount -= 1)
    {
        cout << amount << " bottles of beer on the wall\n"
            << amount << " bottles of beer\n"
            << "Take 1 down, pass it around\n"
            << amount - 1 << " bottles of beer on the wall\n\n";
}
        if (amount < 2)
        status =  false;
{
        cout << "invalid value";
}
}

【问题讨论】:

  • 您的 bottleAmount() 函数不会在所有路径上返回。这是未定义的行为。编译时应该会看到一个警告。不要忽略编译器警告!
  • 返回bool 的函数必须始终返回一个值。如果测试为真,您的 if (bottles &gt; 2) 分支根本不会返回值。在任何情况下,您的 main 对函数的返回值都不做任何事情,所以它也可能不返回一个。选择一个 - 您要么使用返回值并确保函数始终返回 1,要么将函数更改为不返回值并在该函数中进行测试。
  • 不,我从来没有用过橡皮鸭
  • 也许你应该试着给你的橡皮鸭一个机会来解释你需要做什么。

标签: c++ methods boolean


【解决方案1】:

使用 void 函数(不返回值的函数)当然可以做得更好。您可能想改变这样一个事实,即不知何故 amount 变成 bottles 并且计算机应该知道这一点,而无需将值复制到 bottles

#include <iostream>

using namespace std;

void bottleAmount(int amount); // function prototype

    int main()
        
        {
               int amount = 0; // initialize to zero
               cout << "How many bottles of beer on the wall? ";
               cin >> amount;
        
               bottleAmount(amount);
               return 0; // generally it is a good idea to properly end a program
           
        }
    
    void bottleAmount(int amount)
    {
     if (amount >= 2) 
            {
                cout << amount << " bottle(s) of beer on the wall\n"
                    << amount << " bottle(s) of beer\n"
                    << "Take 1 down, pass it around\n"
                    << amount - 1 << " bottle(s) of beer on the wall\n\n";
            }
     else 
            {
                cout << amount << " bottle of beer on the wall\n"
                    << amount << " bottle of beer\n"
                    << "Take 1 down, pass it around\n"
                    << "No more bottles of beer on the wall\n";
            }
    }

【讨论】:

  • 这很有帮助,因为我看到我在 main 中搞砸了。虽然我仍然需要弄清楚如何使它成为布尔值,但我明白这就是我遇到问题的原因
  • 我把它调整到这个,但我仍然收到错误消息
  • 如果是这种情况,我不会让函数返回布尔值,除非您的任务要求您这样做。我会保留函数bottle amount void,但在函数内部有布尔逻辑。您的原始代码存在很多问题,但是您是否理解当您将函数命名为 bool bottleAmount(); bool 时应该是返回类型?如在布尔值返回给函数调用?我建议参考一本好书或网站。询问您遇到的每一个作业问题可能会非常耗时。
  • 你为什么要替别人做作业?
  • 我现在明白了,谢谢你的解释。此外,这只是去年的一项作业,我正在做练习以再次了解一些基础知识。我昨天做了一个更简单的版本,但仍然遇到问题。
猜你喜欢
  • 2016-10-06
  • 2020-04-03
  • 2018-07-17
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
相关资源
最近更新 更多