【发布时间】: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 > 2)分支根本不会返回值。在任何情况下,您的main对函数的返回值都不做任何事情,所以它也可能不返回一个。选择一个 - 您要么使用返回值并确保函数始终返回 1,要么将函数更改为不返回值并在该函数中进行测试。 -
不,我从来没有用过橡皮鸭
-
也许你应该试着给你的橡皮鸭一个机会来解释你需要做什么。