gpt4 book ai didi

c - 我需要一些帮助来用 C 而不是 C++ 来减去两个数组

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

这应该是一个简单的任务,但我就是做不到。该程序必须创建一个原型(prototype)函数 minus 来计算两个数组之间的差异并将结果返回到第三个数组中。在 main 中,它必须将数组的值传递给原型(prototype)函数,然后打印三个数组的值。这是我到目前为止所做的。

#include <stdio.h>
#define NUM 10
int subtract (int [], int [], int);
int main()
{
int x[NUM] = {1, 2 , 3, 4, 5, 6, 7, 8, 9, 10};
int y[NUM] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int result[NUM];
int i;
result[NUM] = subtract( x, y, NUM);

printf("The numbers in the first array are:\n");
for (i=0; i < NUM; i++)
{
printf("%d", x[i]);
}
printf("The numbers in the second array are: %d\n", y[NUM]);
for (i=0; i < NUM; i++)
{
printf("%d", y[i]);
}
printf("The the first array subtracted from the second array is: %d\n", result[NUM]);
for (i=0; i < NUM; i++)
{
printf("%d", result[i]);
}
return 0;
}

最佳答案

最好的解决方案是将数组传递给函数,就像这样

#include <stdio.h>
#define NUM 10

void subtract (int *, int *, int *, int);
int main()
{
int x[NUM] = {1, 2 , 3, 4, 5, 6, 7, 8, 9, 10};
int y[NUM] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int result[NUM];
int i;

subtract(x, y, result, NUM);

printf("The numbers in the first array are\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", x[i]);
printf("The numbers in the second array are\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", y[i]);
printf("The the first array subtracted from"
" the second array is\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", result[i]);
return 0;
}

void subtract(int *x, int *y, int *result, int size)
{
for (int i = 0 ; i < size ; ++i)
result[i] = y[i] - x[i];
}

注意:x[NUM] 和其他类似的未定义,因为数组索引从 0NUM - 1 ,因此当您尝试读取 x[NUM] 时,程序会调用未定义行为

如果您希望 subtract() 返回“数组”,则需要 malloc(),就像这样

int *
subtract(int *x, int *y, int size)
{
int *result;
result = malloc(size * sizeof(*result));
if (result == NULL)
return NULL;
for (int i = 0 ; i < size ; ++i)
result[i] = y[i] - x[i];
return result;
}

然后在 main() 中,您只需声明一个指针并在它不为 NULL 时使用它,当您使用完它时,调用 free()

int 
main(void)
{
int x[NUM] = {1, 2 , 3, 4, 5, 6, 7, 8, 9, 10};
int y[NUM] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int *result;
int i;

result = subtract(x, y, NUM);
if (result == NULL)
return -1; // Failure allocating memory
printf("The numbers in the first array are\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", x[i]);
printf("The numbers in the second array are\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", y[i]);
printf("The the first array subtracted from"
" the second array is\n");
for (i = 0 ; i < NUM ; i++)
printf("%d ", result[i]);
free(result); // It's not strictly necessary since this is the end
// of the program, but you better get used to it.
return 0;
}

您的情况并不真正需要第二种解决方案。它只是向您展示如何做到这一点。最好的方法是第一个解决方案。

关于c - 我需要一些帮助来用 C 而不是 C++ 来减去两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34375586/

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