用C平方根用牛顿迭代法 [英] Square root in C using Newton-Raphson method

查看:126
本文介绍了用C平方根用牛顿迭代法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code,我想更换终止条件为:若猜测广场和x的比率接近于1,while循环应该终止。我尝试了各种前pressions,但没有运行code正确。任何建议?

 #包括LT&;&stdio.h中GT;
绝对浮动(浮动X)
{
     如果(X℃,)
         X = -x;
     返回X;
}浮广场(浮X)
{
    浮猜测= 1;    而(绝对(猜猜猜* - X)> = 0.0001)
        猜=((X /猜测)+猜测)/ 2;    返回的猜测;
}INT主要(无效)
{
    的printf(2的平方根%F \\ N,正方形(2));
    输出(3平方根%F \\ N,方(3));
    返回0;
}


解决方案

打了答案:while语句应该是这样的:

 而(absoluteValue((猜猜*)/ X  -  1.0)> = 0.0001)

In the following code, I want to replace the termination condition to: if the ratio of guess square and x is close to 1, while loop should terminate. I tried various expressions, but none run the code properly. any suggestion?

# include<stdio.h>
float absolute(float x)
{
     if (x < 0)
         x = -x;
     return x;
}

float square(float x)
{
    float guess = 1;

    while(absolute(guess*guess - x) >= 0.0001 )
        guess = ((x/guess) + guess) / 2;

    return guess;
}

int main(void)
{
    printf("square root of 2 is %f\n", square(2));
    printf("square root of 3 is %f\n", square(3));
    return 0;
}

解决方案

hit the answer: while statement should be like this:

 while  ( absoluteValue((guess * guess) / x  - 1.0) >= 0.0001 ) 

这篇关于用C平方根用牛顿迭代法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆