這是我正在研究的一個小硬幣翻轉程序。我試圖從函數傳遞一個變量promptUser();至flipCoin();。我知道你可以在main函數中創建一個局部變量,但是我想將提示組織成函數。C++:將主函數外部的變量從主函數傳遞到主函數內部
是否有辦法通過flipCount value from 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;
}
}
您必須將變量存儲在某處,以便您擁有以下選項:a)有一個全局變量來存儲flipCount - 這通常是一個糟糕的主意; b)主要有一個局部變量 - 你不想要的; c)使'promptUser()'返回一個int並將其作爲參數傳遞給'flipCoin()',例如'flipCoin(promptUser);'。 – jaho
選項c)比選項b)更實用嗎? –