C++:将变量从main外部的函数传递到main内部的函数调用

标签 c++

这是我正在开发的一个抛硬币小程序。我正在尝试将变量从函数 promptUser(); 传递到 flipCoin();。我知道您可以在 main 函数中创建一个局部变量,但我想将提示组织成函数。

有没有办法将 flipCount 值从 promptUser(); 函数传递到 flipCoin(); 函数?

我花了一些时间在谷歌上寻找一种方法来做到这一点(如果有的话),但我认为我无法正确表达我想做的事情,或者这不是它的完成方式。但是,如果有人了解我要实现的目标,或者为什么我不应该这样做,我将不胜感激。谢谢

#include <iostream>
#include <cstdlib>
#include <time.h>

// function prototype
void promptUser();
void flipCoin(time_t seconds);

// prefix standard library
using namespace std;

const int HEADS  = 2;
const int TAILS = 1;

int main(){

    time_t seconds;
    time(&seconds);
    srand((unsigned int) seconds);

    promptUser();
    flipCoin(seconds);
    return 0;
}

void promptUser(){
    int flipCount;
    cout << "Enter flip count: " << endl;
    cin >> flipCount;
}

void flipCoin(time_t seconds){
    for (int i=0; i < 100; i++) {
        cout << rand() % (HEADS - TAILS + 1) + TAILS << endl;
    }
}

最佳答案

只需将 flipCount 返回给 main,然后让 main 将其作为参数传递给 flipCoin

int main() {
  // ...
  // Get the flip count from the user
  int flipCount = promptUser();
  // Flip the coin that many times
  flipCoin(seconds, flipCount);
  // ...
}

int promptUser() {
  int flipCount;
  cout "Enter flip count: " << endl;
  cin >> flipCount;
  // Return the result of prompting the user back to main
  return flipCount;
}

void flipCoin(time_t seconds, int flipCount) {
  // ...
}

main 视为负责。首先 main 命令“提示用户输入翻转次数!” promptUser 函数按照它的指示进行操作,将翻转次数返回给 main。然后 main 说“现在我知道用户想要抛多少次了……所以抛硬币那么多次!”将该数字传递给 flipCoin 以执行该工作。

main              promptUser      flipCoin
  |                   :               :
  |------------------>|               :
    "How many flips?" |               :
                      |               :
  |<------------------|               :
  |         3         :               :
  |                   :               :
  |---------------------------------->|
        "Flip the coin 3 times!"      |
                      :               |
  |<----------------------------------|
  |        <void>     :               :
  V
 END

关于C++:将变量从main外部的函数传递到main内部的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594515/

相关文章:

c++ - 断言失败 Auto_Ptr 不可延期

c++ - 如何在 Fedora 27 上仅安装和使用 Clang-Format?

c++ - 查找字符串可以减少为0的步骤数

c++ - 传递性 add_custom_command 依赖关系未结转

c++ - 需要 C++ 中的枚举类型转换解释

c++ - 如何正确传递参数?

c++ - gcc std::可选和打包结构成员的问题

c++ - ctypes如何将字符串从python传递给c++函数,以及如何将字符串从c++函数返回给python

c++ - 在模板类中重载 operator++

c++ - 在windows终端中输出unicode字符