而牛顿-拉斐逊C中的循环不起作用 #包括 #包括 #包括 浮点数f(浮点数x); 浮点数df(浮点数x); void main() { 浮点x0,x1,最大误差,误差,g,e1,e2,e3; printf(“NEWTON-RAPHSON程序”\n\n); printf(“输入x0:”); scanf(“%f”、&x0); printf(“输入允许的错误(百分比):”; scanf(“%f”&最大错误); while(错误>最大错误){ g=f(x0)/df(x0); x1=x0-g; printf(“x1:%.6f”,x1); e1=x1-x0; e2=e1/x1; e3=abs(e2); 误差=e3*100; printf(“错误:%.6f”,错误); x0=x1; } } 浮点数f(浮点数x) { 返回功率(x,2)+3*x+2; } 浮动df(浮动x) { 返回2*x+3; }
有人能告诉我为什么while循环不起作用吗?它只在允许的错误行之前进行询问,然后程序结束。“NZEC”代码也有运行时错误。而牛顿-拉斐逊C中的循环不起作用 #包括 #包括 #包括 浮点数f(浮点数x); 浮点数df(浮点数x); void main() { 浮点x0,x1,最大误差,误差,g,e1,e2,e3; printf(“NEWTON-RAPHSON程序”\n\n); printf(“输入x0:”); scanf(“%f”、&x0); printf(“输入允许的错误(百分比):”; scanf(“%f”&最大错误); while(错误>最大错误){ g=f(x0)/df(x0); x1=x0-g; printf(“x1:%.6f”,x1); e1=x1-x0; e2=e1/x1; e3=abs(e2); 误差=e3*100; printf(“错误:%.6f”,错误); x0=x1; } } 浮点数f(浮点数x) { 返回功率(x,2)+3*x+2; } 浮动df(浮动x) { 返回2*x+3; },c,C,有人能告诉我为什么while循环不起作用吗?它只在允许的错误行之前进行询问,然后程序结束。“NZEC”代码也有运行时错误。while(error>maxerror){ 此处的while循环不起作用,因为error>maxerror没有给出true,这是因为您没有初始化error(值为0.0f),并且maxerror在到达while循环内的条件时更大,您可以在声明它时进行初始化,如下所示: float error=22.42 或者可以通过用户输入,如: scanf(“%f”,&error);初始的
while(error>maxerror){
此处的while循环不起作用,因为error>maxerror
没有给出true,这是因为您没有初始化error
(值为0.0f),并且maxerror
在到达while循环内的条件时更大,您可以在声明它时进行初始化,如下所示:
float error=22.42
或者可以通过用户输入,如:
scanf(“%f”,&error);
初始的错误值是什么?您没有初始化它。而且pow()
不返回浮点,它返回双精度。读取未初始化的错误
是未定义的行为(不是0f
)。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float f(float x);
float df(float x);
void main()
{
float x0, x1, maxerror, error, g, e1, e2, e3;
printf("NEWTON-RAPHSON PROGRAM \n\n");
printf("Enter x0 : ");
scanf("%f",&x0);
printf("Enter allowed error (in percentage): ");
scanf("%f", &maxerror);
while(error>maxerror){
g=f(x0)/df(x0);
x1=x0-g;
printf("x1 : %.6f",x1);
e1=x1-x0;
e2=e1/x1;
e3=abs(e2);
error=e3*100;
printf("error : %.6f",error);
x0=x1;
}
}
float f(float x)
{
return pow(x,2)+3*x+2;
}
float df(float x)
{
return 2*x+3;
}