编程小白求助,计算牛顿迭代法,为什么编出来的程序输出为 -nan
#include <stdio.h>#include <math.h>
int main(){
double newton(double a, double b, double c,double x_0);
double x_n = newton(1,1,0.25,-1);
printf("x_n is:%lf",x_n);
return 0;
}
double newton(double a, double b, double c, double x_0) {
double x_n = x_0;
double f,fd;
f = a*x_n*x_n+b*x_n + c;
while(fabs(f)>0.001){
f = a*x_n*x_n+b*x_n+c;
fd = 2*a*x_n +b;
x_n = x_n + f/fd;
}
return x_n;
} 你的 "牛顿迭代法" 是用来算什么的? #include <stdio.h>
#include <math.h>
int main(){
double newton(double a, double b, double c,double x_0);
double x_n = newton(1,1,0.25,-1);
printf("x_n is:%lf",x_n);
return 0;
}
double newton(double a, double b, double c, double x_0) {
double x_n=x_0;
double f,fd;
do{
x_0=x_n;
f = a*x_0*x_0+b*x_0+c;
fd = 2*a*x_0 + b;
x_n = x_0-f/fd;
}while(fabs(f)>0.001);
return x_n;
}
这个是正确的程序 但是不明白为什么要x_0=x_n #include <stdio.h>
#include <math.h>
int main(){
double newton(double a, double b, double c,double x_0);
double x_n = newton(1,1,0.25,-1);
printf("x_n is:%lf",x_n);
return 0;
}
double newton(double a, double b, double c, double x_0) {
double x_n=x_0;
double f,fd;
while(fabs(f)>0.001){
x_0=x_n;
f = a*x_0*x_0+b*x_0+c;
fd = 2*a*x_0 + b;
x_n = x_0-f/fd;
}
return x_n;
}
想先判断 再执行 把do while换成了while 输出的值从正确的 -0.51.... 变成了-1.0000 Earl_Flo 发表于 2022-11-7 21:17
#include
#include
#include <stdio.h>
#define abs(n) ((n) >= 0 ? (n) : -(n))
double newton(double a , double b , double c , double x0)
{
double f , fd , x1 = x0 ;
do {
x0 = x1 ;
f = a * x0 * x0 + b * x0 + c ;
fd = 2 * a * x0 + b ;
x1 = x0 - f / fd ;
} while(abs(x1 - x0) > 1e-15) ;
return x1 ;
}
int main(void)
{
printf("x = %lf\n" , newton(1 , 1 , 0.25 , -1)) ;
}
编译、运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
x = -0.500000
D:\\C> jackz007 发表于 2022-11-7 21:54
编译、运行实况:
谢谢回答 但是回答和我提的问题不太一样 Earl_Flo 发表于 2022-11-7 22:41
谢谢回答 但是回答和我提的问题不太一样
有什么不一样? jackz007 发表于 2022-11-7 22:41
有什么不一样?
正确代码我已经的出来了 我只是想知道我的另外两个和正确的那个有什么不一样 第二个代码是个正确的我的题目是当f<=0.001时就结束程序了,而且也不需要abs n。 我就是想弄明白为什么我写的不对 我想使用while语句 你写的这个程序之前在网上看见过了谢谢 本帖最后由 jackz007 于 2022-11-7 23:08 编辑
Earl_Flo 发表于 2022-11-7 22:56
正确代码我已经的出来了 我只是想知道我的另外两个和正确的那个有什么不一样 第二个代码是个正确的我的 ...
你只是笼统说了一个 "牛顿迭代法" ,至于计算什么也不知道,我辛辛苦苦在网上查资料,才猜出你是想求一元二次方程的根,然后,才参考别人的算法原理(网上没有找到计算一元二次方程根的代码),比照你的参数写出了这个代码,我才原创的东西,你却说在网上见过??? jackz007 发表于 2022-11-7 23:04
你只是笼统说了一个 "牛顿迭代法" ,至于计算什么也不知道,我辛辛苦苦在网上查资料,才猜出你是 ...
我也是第一次发帖 可能这个题比较基础 我再csdn上看到很多极度相似的 如有冒犯 很抱歉
页:
[1]