gpt4 book ai didi

c - 用C语言求解微分方程时错误答案

转载 作者:行者123 更新时间:2023-11-30 16:15:55 25 4
gpt4 key购买 nike

我是 C 编程新手,正在编写一个程序来求解简单的微分方程,该方程将输出作为 x 的值。但我没有得到正确的结果。

我得到了正确的方程值,但微分方程的值是错误的。代码编译时没有任何警告或错误。

#include <stdio.h>
#include <conio.h>
#include <math.h>

float poly(float a[], int, float);
float deriv(float a[], int, float);

int main()
{
float x, a[10], y1, dy1;
int deg, i;

printf("Enter the degree of polynomial equation: ");
scanf("%d", &deg);

printf("Ehter the value of x for which the equation is to be evaluated: ");
scanf("%f", &x);

for(i=0;i<=deg;i++)
{
printf("Enter the coefficient of x to the power %d: ",i);
scanf("%f",&a[i]);
}

y1 = poly(a, deg, x);
dy1 = deriv(a, deg, x);

printf("The value of polynomial equation for the value of x = %.2f is: %.2f",x,y1);
printf("\nThe value of the derivative of the polynomial equation at x = %.2f is: %.2f",x,dy1);

return 0;
}

/* function for finding the value of polynomial at some value of x */

float poly(float a[], int deg, float x)
{
float p;
int i;

p = a[deg];

for(i=deg;i>=1;i--)
{
p = (a[i-1] + x*p);
}

return p;
}

/* function for finding the derivative at some value of x */
float deriv(float a[], int deg, float x)
{
float d[10], pd = 0, ps;
int i;

for(i=0;i<=deg;i++)
{
ps = pow(x, deg-(i+1));
d[i] = (deg-1)*a[deg-1]*ps;
pd = pd + d[i];
}

return pd;
}

最佳答案

你犯了一个简单的逻辑错误。函数中 float deriv(float a[], int deg, float x) 应该是 d[i] = (deg-i)*a[deg-i]*ps; 。所以你的函数看起来像这样

/* function for finding the derivative at some value of x */
float deriv(float a[], int deg, float x)
{
float d[10], pd = 0, ps;
int i;

for(i=0;i<=deg;i++)
{
ps = pow(x, deg-(i+1));
d[i] = (deg-i)*a[deg-i]*ps;
pd = pd + d[i];
}

return pd;
}

祝你 future 一切顺利。

关于c - 用C语言求解微分方程时错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com