Loto game- two same numbers

Jun 28, 2015 at 5:32am
I wrote this little code and sometimes it outputs two same numbers, I do not know why? Thanks and sorry if my english is not ok.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    srand((unsigned)time(NULL));
    int broj;
	int polje[]={0,0,0,0,0,0,0,0,0,0};
	char answer;
	
	do{

	   for(int a=0;a<=9;a++)
	   {
		
	      broj=rand()%15;
	   
	       for(int i=0;i<=9;i++)
	       {
		      if(polje[i]==broj)
			  {
				
				  broj=rand()%15;
				  if(i==0)
					  i-=1;
				  else i=0;
				  continue;
			  }
			 
			   
	       }
		  polje[a]=broj;
	   }
   
	cout<<"Here comes numbers "<<endl;
	for(int i=0;i<10;i++)
		cout<<polje[i]<<endl;
	
	cout<<endl<<"Play again? "<<endl;
	cin>>answer;
	}while(answer=='y'||answer=='Y');
	system("PAUSE");
	
	return 0;
}
Jun 28, 2015 at 6:52am
If after first check broj will be rerolled and happens to be the same number as first array element, it will not be cchecked, as your loop skips first element when you restart it.
Jun 28, 2015 at 8:56am
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
srand((unsigned)time(NULL));
int broj;
int polje[]={0,0,0,0,0,0,0,0,0,0};
char answer;

do{

for(int a=0;a<=9;a++)
{
cout<<"Unesite broj "<<endl;
cin>>broj;//broj=rand()%15;

for(int i=0;i<=9;i++)
{
if(polje[i]==broj)
{
cout<<"Unesite broj drugi "<<i<<endl;
cin>>broj;//broj=rand()%15;
if(i==0)
i-=1;
else i=0;
continue;
}


}
polje[a]=broj;
}

cout<<"Here comes numbers "<<endl;
for(int i=0;i<10;i++)
cout<<polje[i]<<endl;

cout<<endl<<"Play again? "<<endl;
cin>>answer;
}while(answer=='y'||answer=='Y');
system("PAUSE");

return 0;
}
Jun 28, 2015 at 9:18am
thanks, Here is the same, little different code I do not know where is a bug, can you explain me please? I tried to use debugger but I cant find where is error?
Jun 28, 2015 at 10:01am
The problem is here:
1
2
3
if(i==0)
i-=1;
else i=0;
Why do you have different cases? Not to mention that modifying for loop variable is a bad style.
Jun 28, 2015 at 2:21pm
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
srand((unsigned)time(NULL));
int number;
int polje[]={0,0,0,0,0,0,0,0,0,0};
int same_number=0;
int written_to_array=10;
int a=0;



while(written_to_array>0)
{
same_number=0;
number=(rand()%15)+1;
for(int i=0;i<=9;i++)
if(polje[i]==number)
same_number=1;
if(same_number!=1){
polje[a]=number;
a++;
written_to_array-=1;
}
}

cout<<"Numbers"<<endl;
for(int i=0;i<10;i++)
cout<<polje[i]<<endl;

system("PAUSE");

return 0;
}
Jun 28, 2015 at 3:03pm
Yes. That is better. And it does not seems to have errors.
Topic archived. No new replies allowed.