如何从无限循环中获取此随机数生成器?

时间:2016-10-16 22:47:10

标签: c++ arrays loops

我有一份学校作业,我需要创建一个彩票计划。它应该允许用户输入六个数字,然后生成六个随机数用于比较。我得到输入工作,但我遇到一个问题,随机数生成器(位于while循环中)陷入无限循环,我完全不知道是什么导致它,因为我从来没有一个无限循环任何以前的程序。如果有人可以查看代码并可能确定错误,我将非常感激。

#include<iostream>
#include<time.h>

using namespace std;

void randomizeSeed();
int randomRange(int min, int max);
int getInteger();

int main()
{
randomizeSeed();

const int minNumber = 1;
const int maxNumber = 49;
const int Size = 6;
int luckyNumbers[6] = {};
int randomNumber = randomRange(minNumber, maxNumber);
int winningNumbers[6] = {};

cout << "Enter six numbers between 1 and 49...\n";
{
    for (int i = 0; i < Size; i++)
    {
        luckyNumbers[i] = getInteger();
    }
    for (int i = 0; i < Size; i++)
    {
        for (int i = 0; i < Size - 1; i++)
        {
            if (luckyNumbers[i] > luckyNumbers[i + 1])
            {
                int temp = luckyNumbers[i];
                luckyNumbers[i] = luckyNumbers[i + 1];
                luckyNumbers[i + 1] = temp;
            }
        }
    }
    cout << "Lucky Numbers: ";
    for (int i = 0; i < Size; i++)
    {
        cout << luckyNumbers[i] << " ";
    }
    cout << "\n";
    cout << "Press any button to see the Winning Numbers.\n";
    system("pause");

    bool exist = true;
    while (exist == true)
    {
        int count = 0;
        cout << "Winning Numbers: ";
        for (int j = 0; j < 6; j++)
        {
            winningNumbers[j] = randomRange(1, 49);
            cout << winningNumbers[j] << " ";
            system("pause");
        }
    }
}
}

void randomizeSeed()
{
srand(time(NULL));
}

int randomRange(int min, int max)
{
int randomValue = rand() % (max + 1 - min) + min;
return randomValue;
}

int getInteger()
{
int value = 0;
while (!(cin >> value) || (value >= 50) || (value <= 0))
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return value;
}

1 个答案:

答案 0 :(得分:0)

for (int i = 0; i < Size; i++)
    for (int i = 0; i < Size - 1; i++)
        if (luckyNumbers[i] > luckyNumbers[i + 1])
        {
            int temp = luckyNumbers[i];
            luckyNumbers[i] = luckyNumbers[i + 1];
            luckyNumbers[i + 1] = temp;
        }

你有两个循环,它们都使用i。您可能意味着将第二个循环与另一个变量名称一起使用,例如:

for (int i = 0; i < Size; i++)
{
    for (int k = 0; k < Size - 1; k++)
    {
        if (luckyNumbers[i] > luckyNumbers[k + 1])
        {
            int temp = luckyNumbers[i];
            luckyNumbers[i] = luckyNumbers[k + 1];
            luckyNumbers[k + 1] = temp;
        }
    }
}

如果将编译器警告级别设置为4,则编译器应警告您这些错误。尝试解决所有编译器警告。