【问题标题】:Pass a variable to a function\Return a new value with that variable\Repeat until value reaches 0将变量传递给函数\使用该变量返回一个新值\重复直到值达到 0
【发布时间】:2019-01-22 17:58:50
【问题描述】:

我在理解如何正确地将用户输入值传递给函数、从该值中减去 1、返回新值以及将新值放入循环中时遇到问题。所以每次循环执行时,它都会将更新后的值发送给函数,最终到达/停止在 0。这就是我目前所拥有的。

#include "pch.h"
#include <iostream>

using namespace std;

int getBottles(int num);

int main()
{
int num;
int run;
int numBottles;

cout << "Enter the amount of bottle to start with: ";
cin >> num;


if ((num < 0) || (num > 101)) {
    cout << "Error! Number isnt valid!\n";
    return main();
}
else
{
    for (size_t i = 0; i <= run; --i)
    {
        numBottles = getBottles(num);
        cout << "Number of beers on the wall " << numBottles;
    }

}
return 0;
}


int getBottles(int num) {

do {
    num = num - 1;

} while (num > 0);
return num;
}

【问题讨论】:

  • 首先选择一种语言。
  • 我认为,您需要使用此处描述的 Rubber Duck 调试技术:rubberduckdebugging.com 来修复您的代码。

标签: c++ windows visual-studio


【解决方案1】:

int getBottles 将在 num > 0 时从 num 中减去 1,而不是一次。

试试类似的东西

int getBottles(int num) {
    return num-1;
}

你在这里使用

for (size_t i = 0; i <= run; --i)

其中run未初始化,你从0开始递减i。

试试类似的东西

while (num) {
    cout << "Number of beers on the wall " << num;
    num = getBottles(num);
}

如果您希望它在打印出来之前停止,那么墙上就没有啤酒了。

【讨论】:

  • numBottles = getBottles(num); num 将保持不变。无限循环。摆脱 num 以支持 numBottles 或将 numBottles 替换为 num。您的选择。
  • 好收获!我没注意到。
猜你喜欢
  • 1970-01-01
  • 2017-07-23
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多