gpt4 book ai didi

使用递归计算像素

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:14 25 4
gpt4 key购买 nike

我遇到一个问题,我需要计算随机生成的二维数组中 1 的数量。首先用户通过命令行参数输入二维数组的大小,然后用户输入坐标,看他输入的坐标中是否有1,如果坐标恰好落在0,则假设返回 0。否则,如果输入的坐标落在 1 上,那么我应该递归检查右上、右上、右下、下、左下、左和左上。

我遇到的主要问题是我不知道是否可以从数组中读入一个 1。我不知道要将什么放入我的递归方法参数中。我有我的array pointerxcoordycoord,它们是用户输入的内容以及row col 这应该是命令行参数。

我认为其他一切都有效,但我可能是错的。我试过这个递归公式。

if(arr[row][col] == 1)
{
recursive(arr, xcoord-1, ycoord, row, col);
blobsize = blobsize + 1;
//more recursive things down here...
}

检查但没有做任何事情。

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

int recursive(int **arr, int xcoord, int ycoord, int row, int col);//What are the arguments for the recursive function?

int main(int argc, char** argv)
{
int i;//counters
int j;//counters
int xcoord;//x coordinate input
int ycoord;//y coordinate input

//random number generator thing idk lol
srand((unsigned int)time(NULL));

int row = strtol(argv[1], NULL, 0);//ROW from command line arguments (1st number)
int col = strtol(argv[2], NULL, 0);//COL from command line arguments (2nd number)

int *arrStorage = malloc(row * col * sizeof(int));//dynamically allocating memory for 2d array
int **arr = malloc(row * sizeof(int*)); //pointer to pointer to array or whatever

//intializing array
for (i = 0; i < row; i++)
{
arr[i] = arrStorage + col * i;
}

//printing out 2d array
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
arr[i][j] = rand() % 2;
printf("%d\t", arr[i][j]);
}

printf("\n");
}

printf(" ");

//Exit the function when non number is entered
//Otherwise continue
while(1)
{
printf("Enter coordinate i,j (Non numeric to quit) \n");

if(1!=scanf("%d", &xcoord) || 1!=scanf("%d", &ycoord))
{
return 0;
}

printf("Blob size: %d\n", recursive(arr, xcoord, ycoord, row, col));
}

free(arr[0]);
free(arr);

}

int recursive(int **arr, int xcoord, int ycoord, int row, int col)
{
int blobsize = 0;

//This is outside the bounds (BASE CASE)
if(xcoord > row && ycoord > col)
{
return 0;
}
//If the selected xcoord & ycoord is 0
if(arr[xcoord][ycoord] == 0)
{
return 0;
}

else
{
if((arr[xcoord][ycoord]==1))
{
//blobsize = blobsize + 1;
//recursive(arr, xcoord - 1, ycoord, row, col);

}
else
{

}
}

return blobsize;

}

如果你能帮忙,谢谢

编辑:修复了一个关键部分。现在为弄清楚递归部分而死。

最佳答案

OP 正在打印一个随机数,但没有将该数字分配给数组。

简单的赋值然后打印。

// printf("%d\t", rand() % 2);
arr[i][j] = rand() % 2;
printf("%d\t", arr[i][j]);

关于使用递归计算像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063150/

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