我无法弄清楚如何在下面的代码中添加指针。我是结构新手,并没有太多接触它们。我需要能够通过引用将值传递给函数。我不一定需要代码只是一个关于我如何去做或指向正确方向的想法。感谢。
#include <stdio.h>
#include <math.h>
union Data1
{
double x1;
};
union Data2
{
double x2;
};
struct array
{
int n[7];
int sums[7];
int sumt[7];
};
double f(double x);
double simp(int n, double x1, double x2);
double trap(int n, double x1, double x2);
int main()
{
union Data1 data1;
union Data2 data2;
struct array array1;
int i;
FILE *f;
f = fopen("data.dat", "a");
data1.x1 = -INFINITY;
data2.x2 = INFINITY;
printf ("Both integration techniques will run for the following intervals: 1, 10, 25, 50, 100, 1000, 10000\n");
array1.n[0] = 1;
array1.n[1] = 10;
array1.n[2] = 25;
array1.n[3] = 50;
array1.n[4] = 100;
array1.n[5] = 1000;
array1.n[6] = 10000;
for(i=0;i<7;i++)
{
array1.sums[i] = simp(array1.n[i],data1.x1,data2.x2);
array1.sumt[i] = trap(array1.n[i],data1.x1,data2.x2);
}
printf("For the trap rule:\n");
printf("\t\tN\t\t\tSum\n");
for(i=0;i<7;i++)
{
printf("\t\t%d\t\t\t%d\n",array1.n[i],array1.sumt[i]);
}
printf("For the simpson rule:\n");
printf("\t\tN\t\t\tSum\n");
for(i=0;i<7;i++)
{
printf("\t\t%d\t\t\t%d\n",array1.n[i],array1.sums[i]);
}
fprintf(f, "For the simpson rule:\n");
fprintf(f,"\t\tN\t\t\tSum\n");
for(i=0;i<7;i++)
{
fprintf(f,"\t\t%d\t\t\t%d\n",array1.n[i],array1.sums[i]);
}
fprintf(f,"For the trap rule:\n");
fprintf(f,"\t\tN\t\t\tSum\n");
for(i=0;i<7;i++)
{
fprintf(f,"\t\t%d\t\t\t%d\n",array1.n[i],array1.sumt[i]);
}
fclose(f);
return 0;
}
double f(double x)
{
double y;
y = exp(-pow(x,2));
return y;
}
double simp(int n, double a, double b)
{
int i;
double dx, x, sum;
dx = (b-a)/n;
sum = f(a)+ f(b);
for(i=1;i<n;i++)
{
x = a + dx*i;
sum += 2*(1+i%2)*f(x);
}
sum*=dx/3;
return sum;
}
double trap(int n, double a, double b)
{
int i;
double dx, x, sum;
dx=(b-a)/n;
sum = f(a)+f(b);
for(i=1;i<n;i++)
{
x = a + dx*i;
sum += 2*f(x);
}
sum *= dx/2;
return sum;
}
答案 0 :(得分:0)
您尝试使用的语法是初始化。但是你没有初始化,你正在分配。初始化只能在定义变量时完成。
所以你需要这样做:
struct array array1 = {{1,10,25,50,100,1000,10000},{0},{0}};
这会将数组n
初始化为所需的值,并将sums
和sumt
的所有值初始化为0.
答案 1 :(得分:0)
要添加指向结构的指针,你可以这样做:
struct array* array1Pointer = &array1;
然后你可以将array1Pointer传递给你想要的函数。
或者你可以在开头声明一个指针,然后为它指向的对象赋值:
struct array* array1Pointer = malloc(sizeof(struct array));
array1Pointer->n[0] = 1;
array1Pointer->sums[i] = simp(array1Pointer->n[i], data1.x1, data2.x2);