我無法弄清楚如何在下面添加指向我的代碼的指針。我對結構不熟悉,對它們沒有太多的接觸。我需要能夠通過引用將值傳遞給函數。我不一定需要代碼才能知道如何去做或指出正確的方向。謝謝。
#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;
}
什麼不起作用?有什麼辦法? –