我是编程新手,刚开始学习c。我希望创建一个简单的战舰游戏,然后我在生成随机数时遇到问题。我想生成一个与另一个数字范围不重叠的随机数。假设我得到40作为我的第一个随机数,我不希望再次出现40,41,42,43和44。以下是我的代码,我无法弄清楚它有什么问题。
srand(time(NULL));
for(counter = 0; counter < ship_num; counter++){
checked = 0;
while (!checked){
ship_x[counter] = 1 + rand()%56;
ship_y[counter] = 1 + rand()%20;
checked = 1;
for(check = 0; check < counter; check++){
if(ship_y[counter] == ship_y[check]){
int check_x = ship_x[check] + 5;
if(ship_x[counter] >= ship_x[check] && ship_x[counter] <= check_x){
checked = 0;
}
}
}
}
}
定义了所有变量,所以我不会在这里再次定义它。
这基本上是用于生成船舶协调的所有代码。输出如下所示。
0.Coordinates: 5, 47
1.Coordinates: 9, 10
2.Coordinates: 8, 55
3.Coordinates: 12, 51
4.Coordinates: 16, 48
5.Coordinates: 17, 32
6.Coordinates: 7, 24
7.Coordinates: 16, 35
8.Coordinates: 1, 7
9.Coordinates: 7, 36
10.Coordinates: 11, 54
11.Coordinates: 17, 29
12.Coordinates: 6, 24
13.Coordinates: 11, 8
14.Coordinates: 3, 5
15.Coordinates: 2, 5
16.Coordinates: 14, 21
17.Coordinates: 20, 24
18.Coordinates: 4, 18
19.Coordinates: 14, 19
20.Coordinates: 14, 1
21.Coordinates: 13, 48
22.Coordinates: 18, 43
23.Coordinates: 16, 25
24.Coordinates: 4, 30
25.Coordinates: 10, 3
26.Coordinates: 18, 17
27.Coordinates: 4, 56
28.Coordinates: 4, 9
29.Coordinates: 1, 4
30.Coordinates: 14, 29
31.Coordinates: 3, 27
32.Coordinates: 18, 56
33.Coordinates: 9, 9
34.Coordinates: 1, 24
35.Coordinates: 7, 42
36.Coordinates: 5, 3
37.Coordinates: 14, 27
38.Coordinates: 4, 50
39.Coordinates: 15, 8
40.Coordinates: 5, 36
41.Coordinates: 6, 37
42.Coordinates: 14, 44
43.Coordinates: 12, 21
44.Coordinates: 1, 49
45.Coordinates: 17, 41
46.Coordinates: 3, 24
47.Coordinates: 10, 2
48.Coordinates: 12, 13
49.Coordinates: 7, 32
50.Coordinates: 5, 11
51.Coordinates: 5, 10
52.Coordinates: 2, 36
53.Coordinates: 11, 29
54.Coordinates: 1, 45
55.Coordinates: 20, 40
56.Coordinates: 2, 52
57.Coordinates: 19, 28
58.Coordinates: 10, 34
59.Coordinates: 10, 31
60.Coordinates: 13, 18
61.Coordinates: 4, 39
62.Coordinates: 8, 33
63.Coordinates: 13, 26
64.Coordinates: 20, 10
65.Coordinates: 16, 18
66.Coordinates: 18, 35
67.Coordinates: 6, 13
68.Coordinates: 6, 34
69.Coordinates: 6, 30
70.Coordinates: 4, 49
71.Coordinates: 3, 14
72.Coordinates: 6, 8
73.Coordinates: 6, 19
74.Coordinates: 14, 11
75.Coordinates: 6, 55
76.Coordinates: 15, 36
77.Coordinates: 16, 15
78.Coordinates: 7, 31
79.Coordinates: 20, 3
从上面可以看出,坐标68和69是我不希望看到的输出,它太靠近了。
别介意,感谢所有评论。我想我刚刚发现我的代码有什么问题。我删除了比我的数组中的数字大1到4的所有数字,但是我忘了删除那个更小的数字,这就是它一直出现的原因。我的新代码只是解决了它,在这里它是,我希望它可以帮助那些面临同样问题的人。
srand(time(NULL));
for(counter = 0; counter < ship_num; counter++){
checked = 0;
while (checked == 0){
ship_x[counter] = 1 + rand()%56;
ship_y[counter] = 1 + rand()%20;
checked = 1;
for(check = 0; check < counter; check++){
if(ship_y[counter] == ship_y[check]){
if(ship_x[counter] <= ship_x[check] + 5 && ship_x[counter] >= ship_x[check] - 5){
checked = 0;
}
}
}
}
}