gpt4 book ai didi

c - 使用指针从 C 函数返回数组

转载 作者:行者123 更新时间:2023-11-30 19:35:20 24 4
gpt4 key购买 nike

我正在编写一段代码,其中有一个函数可以生成随机数并将它们放入数组中。我对如何使用指针非常迷茫,希望得到任何帮助。

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

#define MAX_DATA_SIZE 10
void generate_data(float input_buffer[]); /*prototyping the function*/

int main(void)
{
float input_buffer[MAX_DATA_SIZE + 2] = { 0 };
/*calls the array and prints it*/
return 0;
}

void generate_data(float input_buffer[])
{
int no_of_data_points;
int function_ID = 0;

srand(time(NULL));

no_of_data_points = 2 + rand() % (MAX_DATA_SIZE - 2 + 1); /*generates number of data points that ranges from 2 to MAX DATA SIZE*/
function_ID = 1 + rand() % (4 - 1 + 1); /*generates function ID that ranges from 1 to 4*/

input_buffer[0] = no_of_data_points;
input_buffer[1] = function_ID;

int i = 2; /*counter for input buffer array*/

while (i <= no_of_data_points) {
input_buffer[i] = (float)rand() / RAND_MAX;
i++;
}
return input_buffer;
}

最佳答案

请检查以下源代码。检查代码中的注释。

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

#define MAX_DATA_SIZE 10
void generate_data(float input_buffer[]); /*prototyping the function*/

int main(void) {
float input_buffer[MAX_DATA_SIZE + 2] = { 0 };
int i = 0; /*counter for input buffer array*/

generate_data(input_buffer); /* Generate Random data*/

while (i < input_buffer[0]+2) { /* Print arrey from the begining*/
printf("input_buffer[%d] = %f\n",i,input_buffer[i]);
i++;
}

return 0;
}

void generate_data(float input_buffer[])
{
int no_of_data_points;
int function_ID = 0;

srand(time(NULL));

no_of_data_points = 2 + rand() % (MAX_DATA_SIZE - 2 + 1); /*generates number of data points that ranges from 2 to MAX DATA SIZE*/

printf("------> %d\n",no_of_data_points); /* Just for understanding*/

function_ID = 1 + rand() % (4 - 1 + 1); /*generates function ID that ranges from 1 to 4*/

input_buffer[0] = no_of_data_points;
input_buffer[1] = function_ID;

int i = 2; /*counter for input buffer array*/

while (i < no_of_data_points+2) { /* Store the "no_of_data_points" to array from i = 2*/
input_buffer[i] = (float)rand() / RAND_MAX;
i++;
}

return; /* Return type is void*/
}

关于c - 使用指针从 C 函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42802853/

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