2016-11-15 55 views
0

我無法使我的功能正確適用於我正在寫作業作業的程序。該任務要求我寫一個抽獎模擬,其中用戶猜測1到40之間的7個數字。然後將這些數字與來自單獨函數的隨機生成的數字進行比較。該功能意味着在陣列中索要和保存7號:將數字輸入到數組中

const int size = 7; 

int getLottoPicks(int userNum[size]) { //collects and stores the user input 

for (int i = 0; i < size; i++) { 
    cout << "Please enter number " << i+1 << ": "; 
    cin >> userNum[i]; 

if (userNum[i] < 1 || userNum[i] > 40) { //keeps the number between 1 and 40 
    cout << "The number must between 1 and 40." << endl 
     << "Please enter another number: "; 
    cin >> userNum[i]; 
} 
} 

return userNum[size]; 
} 

目前這個函數輸出的東西發瘋似的0096F71C,而不是輸入的號碼。

我需要做些什麼修改才能在調用時輸出7位數組? 另外,找到並防止用戶輸入重複值的最佳方法是什麼?

在此先感謝。

回答

0

您的函數不會輸出提示以外的任何內容。它會在數組的末尾返回一個元素。你有未定義的行爲在這裏進行。

我建議你不需要返回任何東西,因爲你的函數已經插入到它給出的數組中。現在要解決它,你可以做到以下幾點:

const int size = 7; 

void getLottoPicks(int userNum[size]) { //collects and stores the user input 

    for (int i = 0; i < size; i++) { 
    cout << "Please enter number " << i+1 << ": "; 
     cin >> userNum[i]; 

    if (userNum[i] < 1 || userNum[i] > 40) { 
     cout << "The number must between 1 and 40." << endl 
      << "Please enter another number: "; 
     cin >> userNum[i]; 
    } 

    for (int j = i; j > 0; --j) { 
     if (userNum[i] == userNum[j]) { 
     cout << "Already entered this number"; 
     } 
    } 
    } 
} 
+0

我很感激幫助。但是,當我在程序中進行這些更改時,我在調用該函數時創建了一個錯誤。我打電話給: _userTicket [size] = getLottoPicks(userTicket); _ 和我收到的錯誤說:_「'=':無法從'void'轉換爲'int'」._我是不是正確地調用它? –

+0

@MaxOrozco,是的,你是。只需聲明數組'int userTicket [size];'然後在單獨的一行中調用該函數。'getLottoPicks(userTicket);' – StoryTeller