gpt4 book ai didi

c - Newton-Raphson C 中的 While 循环不起作用

转载 作者:行者123 更新时间:2023-11-30 20:03:34 26 4
gpt4 key购买 nike

#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;
}

有人可以告诉我为什么“while”循环不起作用吗?它只会询问,直到出现允许的错误行,然后程序结束。 “NZEC”代码还存在运行时错误。

最佳答案

while(error>maxerror){

这里的 while 循环不起作用,因为 error>maxerror 没有给出 true,那是因为您还没有初始化 error(将具有值 0.0f)并且当达到 while 循环内的条件时, maxerror 会更大,您可以在声明它时初始化它,如下所示:

float 错误=22.42

或者可以通过用户输入,例如:

scanf("%f", &error);

关于c - Newton-Raphson C 中的 While 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344290/

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