我是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