我是C++的新手,并试图为大学项目创建一个彩票游戏。当输入新变量时,C++ For-Loop会卡住
我有一个for循环来检查输入数组中没有重复的数字。当你拿出代码段来产生随机数时,这种方法非常好。
只要我将随机数部分添加回来,for循环就会卡住。它会不断告诉我,当它试图存储第一个号码时,我已经输入了该号码。
我附上了我所有的代码,如果你不需要这些,请致歉。
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
//int loto[6];
int main()
{
int numbers[6];
//void rand_num(int loto[6], int count);
int loto[6]; //used to store the loto numbers
//int james = 0;
//int l,j; //used in checking any duplicated
srand(time(0));
for(int count=0; count<6; count++)
{
loto[count] = (rand()%49)+1;
cout << loto[count] << endl;
}
//declares the variable i to increase each time a number is entered.
//this will only go as high as 6
for(int i=0;i<6;i++)
{
cout<<" " << i<<" : Please enter your lottery numbers: "<<endl;
cin>>numbers[i];
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
//checks to see if the first number entered is above 50 or = to 0 and rejects it
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
//----------------------------------------------------------------------------
//this section of code is a loop within a loop to check the number entered against all numbers already stored.
//makes l the same as i effectively
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if(numbers[l] == numbers[j])
do
{
{
cout << "Number has already been chosen, please re-enter number " << endl;
cout << endl;
cin >>numbers[i];
//checks the number that is re-entered is not <50 or = 0
//if so it rejects it and asks for another as above.
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
}
}
while (numbers[l] == numbers[j]);
}
}
}
//----------------------------------------------------------------------------
//this displays the numbers that have been chosen.
cout << "Your Numbers are: " << endl;
for (int i = 0; i<6; i++)
{
cout << " " << numbers[i];
}
return 0;
}
你有没有试过在你的调试器中的代码,看看发生了什么? – 2015-02-11 10:57:16
我发现注释掉的代码特别有用。 – 2015-02-11 10:57:39
我投票结束这个问题作为题外话,因为没有证据表明在发布之前已经尝试过基本的调试。 – John3136 2015-02-11 10:58:11