Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2529341
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-07-30 13:28:17

用迭代法求。求平方根的迭代公式为:

Xn+1  =  (Xn +a/Xn)

要求前后两次求出的x的差的绝对值小于10-5

看到这个题目,我们可以将式子带入求出Xn+1  ,然后和Xn做差的绝对值与10的-5次方做比较,如果小于则跳出循环。代码如下:

 

#include <stdio.h>
#include <math.h>

int main(int argc, int *argv[]) {
float x=1,x0;
int n;
printf("please intput a number:");
scanf("%d",&n);
while ( n < 0 )
{
      scanf("%d",&n);
}

do
{
    x0 = (x + n/x)/2;
    if (abs(x0 - x) < pow(10,-5))
    {
       break;
    }
    else
    {
       x = x0;
    }
} while (1);


printf("The square root of %d is %f\n",n,x0);
system("pause");
return 0;
}


阅读(9692) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~