2016-11-15 73 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