这是我正在开发的一个抛硬币小程序。我正在尝试将变量从函数 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/