gpt4 book ai didi

c - 程序打印的坐标与我为其生成的坐标不同

转载 作者:行者123 更新时间:2023-11-30 14:34:38 24 4
gpt4 key购买 nike

基本上,我需要我的程序将我手动输入的点放置在网格上(效果很好),然后将一个点随机放置在同一网格上,并根据用户请求重复多次。目前,我的代码打印计算机选择的数字,但不会将它们放置在网格上,直到我键入另一个数字并按 Enter 键,然后将其放置在看似随机的位置。这是我的代码

void placeCShip(){
int a,b;
srand(time(NULL));
a = printf("%d\n", rand()%15);
b = printf("%d\n", rand()%15);
scanf("%d, %d", &a, &b);
if (grid[a][b] == SEA, grid[a][b] != PSHIP){
grid[a][b] = CSHIP;
}
}

这是重复它的函数,当我排除 Cships 时它工作得很好,当我包含它时 Pships 仍然工作,但 Cships 没有给出正确的坐标

void placePShips(){
int i,fleetSize;
printf("\nEnter fleet size : ");
scanf("%d", &fleetSize);
for(i=0;i<fleetSize;i++){
placePShip();
placeCShip();
printGrid();
}
}

我尝试过的;

完全删除 printf,仅使用 rand 函数,解决了告诉我随机坐标的问题,但我仍然需要输入另一个数字并单击 Enter 才能显示

完整代码:

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

#define MAXGRIDSIZE 15
#define SEA '.'
#define PSHIP 'P'
#define CSHIP 'C'
#define BOMB '*'
#define SUNKENSHIP 'v'

unsigned char grid[MAXGRIDSIZE][MAXGRIDSIZE];


//F1
void printGrid(){
int x, y;
printf("\n");
for(y=0; y<MAXGRIDSIZE; y++){
printf("%2d", y);
for(x=0; x<MAXGRIDSIZE; x++){
printf("%3c", grid[y][x]);
}
printf("\n");
}
printf("%2c", ' ');
for(x=0; x<MAXGRIDSIZE; x++){
printf("%3d", x);
}
printf("\n");
}

//F2
void initGrid(){
int x, y;
for(y=0; y<MAXGRIDSIZE; y++){
for(x=0; x<MAXGRIDSIZE; x++){
grid[y][x] = SEA;
}
}
}

//F3
void placePShip(){
int x,y;
printf("\nEnter Ship location: x , y: ");
scanf("%d , %d", &x, &y);
if (grid[y][x] == SEA){
grid[y][x] = PSHIP;
}
}

//F4
void placeCShip(){
int a,b;
srand(time(NULL));
a = rand()%15;
b = rand()%15;
scanf("%d, %d", &a, &b);
if (grid[a][b] == SEA, grid[a][b] != PSHIP){
grid[a][b] = CSHIP;
}
}


//F5
void placePShips(){
int i,fleetSize;
printf("\nEnter fleet size : ");
scanf("%d", &fleetSize);
for(i=0;i<fleetSize;i++){
placeCShip();
placePShip();
printGrid();
}
}

//F6
int main(){
initGrid();
printGrid();
placePShips();
printGrid();

return 0;
}

最佳答案

简短回答:您有不需要的“scanf”调用,这将

该代码混合了 IO 和输入。在使用每个函数之前,请考虑查看每个函数的每个手册页。另外,请注意编译器警告,因为这将为您节省大量调试时间。

从 placeCship 开始:

void placeCShip(){
// Loop until unused location is found.
while ( 1 ) {
int a=rand()%15 ;
int b=rand()%10 ;
// MOVE to 'main': srand(time(NULL));
if (grid[a][b] == SEA){
grid[a][b] = CSHIP;
break ;
}
}
}

对于玩家飞船,请考虑切换到 fgets/sscanf。 “scanf”将使您陷入解析错误的无限循环。

void placePShip(){
// Loop until valid coordinates are entered.
while ( 1 ) {
int x,y;
printf("\nEnter Ship location: x , y: ");
scanf("%d , %d", &x, &y);
if (grid[y][x] == SEA){
grid[y][x] = PSHIP;
break ;
}
}
}

关于c - 程序打印的坐标与我为其生成的坐标不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com