gpt4 book ai didi

c - 我如何概括这个我用来指定 vector 长度的宏?

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:24 29 4
gpt4 key购买 nike

我有两个代码:vector_add.cvector_print.c .两者都要求我分配 vector 长度 N,作为使用 #define N (3) 的宏,其中 3 是长度。我同意 vector_add.c ,但我不想一概而论 vector_print.c适用于任何 vector 长度,然后稍后在另一个代码中分配 vector 长度。我尝试使用 #undef N以不同的方式,但我无法让它工作。

有没有人对我如何概括我的 vector_print 有任何建议?函数适用于任何 vector 长度,N?现在,我只是在使用 #define N (3)对于这两个文件,这对于长度为 3 的 vector 都适用。但我不想在 vector_print.c 中显式分配 vector 长度.我希望它适用于任何 N!

这是 vector_add.c :

#include <vector_print.h>
#include <stdio.h>

// vector length (fixed)

#define N (3)

// ----------------------------------------------------------------------
// vector_add
//
// returns the linear sum of the two vectors and puts them in another
// x: first vector
// y: second vector
// z: solution vector

void
vector_add(double *x, double *y, double *z)
{
for (int i = 0; i < N; i++) {
z[i] += x[i] + y[i];
}
}

// ----------------------------------------------------------------------
// main
//
// test the vector_add() function

int
main(int argc, char **argv)
{
double x[N] = { 1., 2., 3. };
double y[N] = { 2., 3., 4. };
double z[N] = {0.,0.,0.};
vector_add(x, y, z);

printf("x is ");
vector_print(x);
printf("y is ");
vector_print(y);
printf("z is ");
vector_print(z);

return 0;
}

这是 vector_print.c :

#include <stdio.h>

// vector length (fixed)

#define N (3)

// ----------------------------------------------------------------------
// vector_print
//
// prints the elements of an N-element array
// name: name of vector to print

void
vector_print(double *name)
{
for (int i = 0; i < N; i++) {
printf("%g ", name[i]);
}
printf("\n");
}

如有必要,这里是 vector_print.h :

#ifndef VECTOR_PRINT_H
#define VECTOR_PRINT_H

void vector_print(double *name);

#endif

最佳答案

只是在评论中传达解决方案。

你可以做的是像这样将长度传递给那些函数:

void vector_print(double *name, int len);
void vector_add(double *x, double *y, double *z, int len);

这将允许您像这样控制循环:

  for (int i = 0; i < len; i++) { // Note: i < len now, not N
printf("%g ", name[i]);
}

关于c - 我如何概括这个我用来指定 vector 长度的宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54719485/

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