Help! C programming...#include
#include
#define NT double
NT f(NT x, NT y)
{
return x+y;
}
NT rkstep (NT (*func)(NT, NT), NT x, NT y[], NT h, int n, NT *err[])
{
NT k[n], y12[n], y1[n], k12[n];
k[n]=(*func)(x,y[n]);
y12[n]=y[n]+k[n]*h/2;
k12[n]=(*func)(x,y12[n]);
y1[n]=y[n]+k12[n]*h;
*err[n]=fabs(k[n]-k12[n])*h/2;
return y1[n];
}
int main ()
{
int n;
NT x, y[n], h, *err[n], result[n];
x=1;
y[0]=10;
for (n=0;n (more...)
给你改了一下,可以编译了。不过计算数值的步骤可能有逻辑错误。
你的程序里,变量 "h" 没有初始值,导致后面的结果为 0,
不过现在可以编译和运行了,检查一下是不是那些变量都设置对了。
good luck
程序如下
------------------------
#include <stdio.h>
#include <math.h>
#define NT double
NT f(NT x, NT y)
{
return x+y;
}
NT rkstep (NT x, NT y, NT h, NT *err_i)
{
NT k, y12, y1, k12;
k = f(x,y);
y12 = y + k*h/2;
k12 = f(x, y12);
y1 = y + k12*h;
*err_i = fabs(k-k12)*h/2;
return y1;
}
int main ()
{
int i = 0; // for loop index
NT x = 1;
NT h = 1; // what is the value of "h" ?
// dynamic sized arrays, (actually these are pointers)
NT *y;
NT *err;
NT *result;
int bound = 4; // "bound" is the size of your array
x=1;
// allocate memory for pointers
y = (NT*) malloc(bound*sizeof(NT));
err = (NT*) malloc(bound*sizeof(NT));
result = (NT*) malloc(bound*sizeof(NT));
// ensure memory allocation is successful
if(y == NULL || err == NULL || result == NULL)
{
printf("malloc() error: y, error or result!");
return 0;
}
y[0]=10;
for (i=0; i<bound; i++)
{
result[i]=rkstep(x, y[i], h, &err[i]);
printf("i=%d\n", i);
printf("result=%lf\n\n", result[i]);
}
y[0]=10;
for (i=0; i<bound; i++)
{
result[i]=rkstep(x, y[i], h, &err[i]);
printf("i=%d\n", i);
printf("result=%lf\n\n", result[i]);
}
// free the allocated memory space
free(y);
free(err);
free(result);
return 0;
}
不过现在可以编译和运行了,检查一下是不是那些变量都设置对了。
good luck
程序如下
------------------------
#include <stdio.h>
#include <math.h>
#define NT double
NT f(NT x, NT y)
{
return x+y;
}
NT rkstep (NT x, NT y, NT h, NT *err_i)
{
NT k, y12, y1, k12;
k = f(x,y);
y12 = y + k*h/2;
k12 = f(x, y12);
y1 = y + k12*h;
*err_i = fabs(k-k12)*h/2;
return y1;
}
int main ()
{
int i = 0; // for loop index
NT x = 1;
NT h = 1; // what is the value of "h" ?
// dynamic sized arrays, (actually these are pointers)
NT *y;
NT *err;
NT *result;
int bound = 4; // "bound" is the size of your array
x=1;
// allocate memory for pointers
y = (NT*) malloc(bound*sizeof(NT));
err = (NT*) malloc(bound*sizeof(NT));
result = (NT*) malloc(bound*sizeof(NT));
// ensure memory allocation is successful
if(y == NULL || err == NULL || result == NULL)
{
printf("malloc() error: y, error or result!");
return 0;
}
y[0]=10;
for (i=0; i<bound; i++)
{
result[i]=rkstep(x, y[i], h, &err[i]);
printf("i=%d\n", i);
printf("result=%lf\n\n", result[i]);
}
y[0]=10;
for (i=0; i<bound; i++)
{
result[i]=rkstep(x, y[i], h, &err[i]);
printf("i=%d\n", i);
printf("result=%lf\n\n", result[i]);
}
// free the allocated memory space
free(y);
free(err);
free(result);
return 0;
}