我正在编写一个应该充当彩票的代码。可用的彩票号码是1-50,其中有10。如果用户的号码与10个随机彩票号码之一匹配,则假定用户输入一个号码,程序返回。我把所有这些部分都弄清楚了,但是有一个问题。所有10个彩票号码必须唯一。我已经得到10个唯一的数字1-50,但是它们不是很随机。到目前为止,我编写的代码对我来说似乎是正确的,除了我知道缺少一些东西(以及我可以清理很多代码的事实,但我现在的重点是目标)。现在,如果我运行该程序,它将返回十个零。我需要彩票数组中的每个元素都是1到50之间的唯一数字,并且每次我运行该程序时都产生不同的数字集。任何帮助,将不胜感激。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using std::cout; using std::cin; using std::endl;

void printOut(int[]);
void draw(int[]);
bool check();
int fillFunc[10];

int main()
{
    const int arraySize = 10;
    int win[arraySize] = {};

    srand((unsigned)time(NULL));

    draw(win);
    cout << "Your lottery numbers are: ";
    printOut(win);
}

void draw(int fillFunc[])
{
    int i;
    for (i = 0; i < 10; i++)
    {
        if (check() == true)
            continue;
        fillFunc[i] = 1 + rand() % 50;
    }
}

void printOut(int fillFunc[])
{
    for (int i = 0; i < 10; i++)
    {
        cout << " " << fillFunc[i];
    }
    cout << "\n";
}

bool check()
{
    for (int i = 0; i < 10; ++i)
    {
        if (fillFunc[i] == i)
            return true;
    }
    return false;
}


(也不要问我为什么数组具有名称“ win”,这就是我的教授要我称之为的名字)

最佳答案

考虑到您的限制,这就是我会做的。填充数组时,无需检查数字是否唯一,只需将数组传递到选择数字的函数中,以便它可以返回唯一值。

我还删除了冗余全局阵列。如果您忘记将正在使用的本地数组传递给任何功能,则可能是错误的来源。

#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int getUniqueNumber(int fillFunc[])
{
    while(true)
    {
        //pick number
        int val = 1 + rand() % 50;
        //assume it's unique
        bool unique = true;
        for (int i = 0; i < 10; ++i)
        {
            //if another number matches, it isn't unique, choose again
            if (fillFunc[i] == val)
            {
                unique = false;
                break;
            }
        }
        //if it is unique, return it.
        if (unique)
        {
            return val;
        }
    }
    //never reached, but avoids an all control paths must return a value warning.
    return -1;
}

void draw(int fillFunc[])
{
    for (int i = 0; i < 10; i++)
    {
        fillFunc[i] = getUniqueNumber(fillFunc);
    }
}

void printOut(int fillFunc[])
{
    for (int i = 0; i < 10; i++)
    {
        cout << " " << fillFunc[i];
    }
    cout << "\n";
}

int main()
{
    srand((unsigned)time(NULL));
    const int arraySize = 10;
    int win[arraySize] = {};
    draw(win);
    cout << "Your lottery numbers are: ";
    printOut(win);
    return 0;
}


还有其他也许更好的方法来选择范围内的唯一数字,但是我还是简单地实现和解释。您可以在以下问题中了解其他一些方法:

Unique random numbers in an integer array in the C programming language

Unique (non-repeating) random numbers in O(1)?

关于c++ - 为什么我随机生成的数组仅输出零?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46679650/

10-09 07:51
查看更多