2012-11-27 50 views
0

這是我正在研究的一個小硬幣翻轉程序。我試圖從函數傳遞一個變量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; 
    } 
} 
+0

您必須將變量存儲在某處,以便您擁有以下選項:a)有一個全局變量來存儲flipCount - 這通常是一個糟糕的主意; b)主要有一個局部變量 - 你不想要的; c)使'promptUser()'返回一個int並將其作爲參數傳遞給'flipCoin()',例如'flipCoin(promptUser);'。 – jaho

+0

選項c)比選項b)更實用嗎? –

回答

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說:「現在我知道用戶需要多少次翻轉......所以多次翻轉硬幣!」將該號碼傳遞給flipCoin以執行此項工作。

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

感謝您提高我的理解力,併爲圖表! –

相關問題