2017-04-10 122 views
-1

Problem帶指針問題的結構

我無法弄清楚如何在下面添加指向我的代碼的指針。我對結構不熟悉,對它們沒有太多的接觸。我需要能夠通過引用將值傳遞給函數。我不一定需要代碼才能知道如何去做或指出正確的方向。謝謝。

#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; 
} 
+2

什麼不起作用?有什麼辦法? –

回答

0

你試圖使用的語法是一個初始化。但是你沒有初始化,你是分配。初始化只能在定義變量時完成。

所以,你需要做的是這樣的:

struct array array1 = {{1,10,25,50,100,1000,10000},{0},{0}}; 

這初始化數組n到所需的值,並初始化的sumssumt數值全部清零

0

要添加指針結構,你可以這樣做:

struct array* array1Pointer = &array1; 

然後你可以將array1Pointer傳遞給函數y你想要。

或者你也可以在開始時聲明一個指針,然後賦值給它指向的對象:

struct array* array1Pointer = malloc(sizeof(struct array)); 

array1Pointer->n[0] = 1; 
array1Pointer->sums[i] = simp(array1Pointer->n[i], data1.x1, data2.x2);