我需要c代码的帮助。代码实际上运行fyn,但我需要它做更多。该程序是使用Runge Kutta四阶方法求解微分方程组的代码。简而言之,我需要的只是一种方式让我从界面输入问题,而不是从代码内部输入。请帮助任何帮助。
#define X0 1.0
#define Xn 2.0
#define STEPLEN 10
#define Y1 1 //initial condition for y1 at x=0
#define Y2 0 //initial condition for y2 at x=0
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double f1(double x,double y1,double y2)
{
//a function to solve the functions 2 using x and y
return(y2);
}
double f2(double x,double y1,double y2)
{
//a function to solve the functions 1 using x and y
return(x*log(x) - (2*y1)/(x*x) + (2*y2)/x);
}
main()
{
double x,y1[STEPLEN],y2[STEPLEN];
double xmid,k1[2],k2[2],k3[2],k4[2],h = (double)(Xn - X0)/STEPLEN;
x = X0;
y1[0]=Y1;
y2[0]=Y2;
int i;
printf("This are the initial values. y1=%.10f y2=%.10f and h=%f\n\n", y1[0], y2[0],h);
//printf("x\t|k1\t|k2\t|k3\t|k4\t|y\n\n");
for(i=0; i<STEPLEN; i++){
k1[0]=h * f1(x,y1[i],y2[i]);
k1[1]=h * f2(x,y1[i],y2[i]);
xmid = x + h/2.0;
k2[0] = h * f1(xmid, y1[i] + k1[0] * 1/2.0, y2[i] + k1[1] * 1/2.0);
k2[1] = h * f2(xmid, y1[i] + k1[0] * 1/2.0, y2[i] + k1[1] * 1/2.0);
k3[0] = h * f1(xmid, y1[i] + k2[0] * 1/2.0, y2[i] + k2[1] * 1/2.0);
k3[1] = h * f2(xmid, y1[i] + k2[0] * 1/2.0, y2[i] + k2[1] * 1/2.0);
k4[0] = h * f1(x + h, y1[i] + k3[0] , y2[i] + k3[1]);
k4[1] = h * f2(x + h, y1[i] + k3[0] , y2[i] + k3[1]);
y1[i+1] = y1[i] + (k1[0] + 2*k2[0] + 2*k3[0] + k4[0])/6;
y2[i+1] = y2[i] + (k1[1] + 2*k2[1] + 2*k3[1] + k4[1])/6;
printf("When x=%f\n",x+h);
printf("k1 for y1=%.10f\n",k1[0]);
printf("k1 for y2=%.10f\n",k1[1]);
printf("k2 for y1=%.10f\n",k2[0]);
printf("k2 for y2=%.10f\n",k2[1]);
printf("k3 for y1=%.10f\n",k3[0]);
printf("k3 for y2=%.10f\n",k3[1]);
printf("k4 for y1=%.10f\n",k4[0]);
printf("k4 for y2=%.10f\n",k4[1]);
printf("y1 when x is %f=\t%.10f\n",x+h,y1[i+1]);
printf("y2 when x is %f=\t%.10f\n\n",x+h,y2[i+1]);
// printf("%f %f %f %f %f %f %f %f %f %f \n",k1[0],k1[1],k2[0],k2[1],k3[0],k3[1],k4[0],k4[1],y1[i+1],y2[i+1]);
x = x+h;
}
system("pause");
}
答案 0 :(得分:0)
可以简单地做
double X0, Xn;
fputs("Enter X0\n", stdout);
if (sscanf("%lf", &XO) != 1) Handle_EOForInputProblem();
fputs("Enter Xn\n", stdout);
if (sscanf("%lf", &Xn) != 1) Handle_EOForInputProblem();
...
或者创建一个帮助函数来提示,处理用户I / O问题,并阅读各种double
。
int Mayor_Read_Double(const char *prompt, double *dest) {
char buffer[100];
for (;;) {
fputs(prompt, stdout);
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return -1;
}
char *endptr;
errno = 0;
double number = strtod(buffer, &endptr);
if (errno && number != 0.0) {
fputs("Input out of range\n", stdout);
continue;
}
if (buffer == endptr) { // no conversion
fputs("Invalid input\n", stdout);
continue;
}
// Detect extra garbage
while (isspace((unsigned char) *endptr)) endptr++;
if (*endptr) {
fputs("Extra input\n", stdout);
continue;
}
*dest = number;
return 1;
}
}
double X0, Xn;
if (Mayor_Read_Double("Enter X0\n", &X0) != 1) return 0;
if (Mayor_Read_Double("Enter Xn\n", &Xn) != 1) return 0;
...