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

标签 c

#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/

相关文章:

c - Qsort使用的比较功能-比较(char **)

C头文件依赖

c - 数组中的元素太多!

c - 警告 : pointer targets in passing argument 2 of ‘strcat’ differ in signedness

c - gcc: 错误: 无法识别的命令行选项 ‘-1m’

c - struct_type[1] 是什么意思?

c - 处理 *nix 中多路复用套接字上的读取超时

C: 浮点运算的结果总是归一化的吗?

c - 在C中加密纯文本文件

c - 使数组内容易变的正确语法?