战舰游戏-随机坐标c++
Battleships game - Random co-ordinates c++
好了,我修复了我的代码。我可以生成5个随机坐标并将它们保存在我的数组中,但我需要确保坐标不会重复。我试图将每个坐标保存在一个单独的数组中,并使用if语句,但我不知道如何做到这一点。有人能给我一些建议吗?这是我的代码到目前为止…
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
int *x, *y;
int a, b;
int randNum2, randNum;
char arr[5][5]={{0}};
srand(time(0));
x = &randNum;
y = &randNum2;
for( a = 0 ; a < 5 ; a++ ){
randNum = (rand() % 5);
randNum2 = (rand() % 5);
arr[*x][*y] = 'S';
}
return 0;
}
你的代码不能正常工作的原因有很多!
char arr[5][5] = {{255}};
很可能会做一些你意想不到的事情:它只将arr[0][0]
初始化为255
,然后将所有其他值初始化为0
。
因此,x
和y
的有效范围实际上是在0到4之间,但rand() % 5 + 1
给你一个1到5之间的随机整数。因此,您可以不初始化二维数组的所有项,或者破坏内存。
对于剩余的代码,它不是自给自足的。H
应该是什么?
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
int x, y;
char arr[5][5]={{255}};
srand(time(0));
for(x = 0; x < 5; x++)
{
for(y = 0; y < 5; y++)
{
int randNum = (rand() % 5) + 1;
int randNum2 = (rand() % 5) + 1;
if(x==randNum && y==randNum2)
cout<< (arr[x][y] = 'H');
else
cout<< (arr[x][y] = 255);
}
cout<<endl;
}
return 0;
}
给出的输出类似于
�����
�����
��H��
�����
�����
�����
��H��
���H�
����H
�����
…等等,有时没有h
现在你告诉我这应该是什么
相关文章:
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- OpenGL 4.3 错误地将第 4 个纹理坐标映射到与第 3 个纹理坐标相同的位置
- 比较两个节点坐标的最佳方法是什么?
- 在 OpenGL 中将笛卡尔世界坐标转换为球面局部坐标
- SDL2 调整窗口大小后如何缩放鼠标坐标?
- 如何在C++中获取坐标?
- 如何将 x.y 坐标的值存储在不同的数组中
- 如何将鼠标坐标转换为"mm"
- 重心坐标并不总是有效(3d)
- 尝试渲染像素坐标时,简单线条渲染失败
- 使用 GTK3 C++获取指针坐标
- 从 CGAL 3D 网格生成中获取顶点坐标的 -6.27744e+66:mesh_implicit_sphere示例
- 我想制作设置鼠标回调函数,以便在仍然按下鼠标左键时连续传递坐标
- 将鼠标悬停在图片框上时,如何显示带有 x-y 坐标的十字准线光标?
- 跳转到通过输入坐标定义的控制台屏幕位置
- QImage::p ixel 和 QImage::setPixel 坐标超出范围误差
- 如何从 3d 对象文件中获取 3d 坐标
- 使用C++中的链表对与原点的距离、x 和 y 坐标进行排序