0

这是我正在研究的一个小硬币翻转程序。我正在尝试从函数promptUser(); 传递一个变量;翻转币();. 我知道您可以在主函数中创建一个局部变量,但我想将提示组织成函数。

有没有办法从promptUser();传递flipCount值?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;
    }
}
4

1 回答 1

2

只需返回flipCountmain,然后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
于 2012-11-27T22:46:18.860 回答