这是我正在研究的一个小硬币翻转程序。我正在尝试将函数 promptUser(); 中的变量传递给 flipCoin(); 。我知道你可以在main函数中创建一个局部变量,但是我想把提示组织成函数。
有没有办法将 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;
}
}
答案 0 :(得分:2)
只需将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