加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

c语言中的平方根函数

(2010-03-28 14:18:40)
标签:

杂谈

今天一上午只编写了一个程序,求一个数的平方根!我们利用Newton迭代法求给定值的绝对值的平方根,下面给出Newton迭代法求平方根的算法过程:

       设置猜测初值为1

       如果 | 猜测值*猜测值-X |<ε,则转到④;(ε指的是一个很小的数

       设置新的猜测值为(X / 猜测值+猜测值)/ 2,返回到②;

       猜测值就是满足要求的X的平方根。

自己编写代码为:

#include<stdio.h>
#include<math.h>
float sqrt(float x);
void main()
{
 float n,sqr;
 char ch;
 while(1)
 {
 printf("\n*****please input the number you want to count!********  \n");
  
 scanf("%f",&n);
 if(n<0)
 {
 printf("\n***********************************************************  \n");
    printf("the input is :%f\n",n);
    printf("the input is a minus !\nso  the number should be converted to a plus\n then  count the result \n");
 printf("\n***********************************************************  \n");
 }
    else
 printf("the input is :%f\n",n);
 sqr=sqrt(n);
 printf("the sqr is :%f\n",sqr);
 ////////////////////////////////
 ch=getchar();
 printf("\n/////////////////////////////////////////////////////////////  \n");
 printf("\n if you want to contine \n please enter the Enter key!\n");
 printf("\nif you want to quit! \nplease enter others key \n");
 printf("\n///////////////////////////////////////////////////////////  \n");
 ch=getchar();
 if(ch!='\n')
  break;
 }
}
float sqrt(float x)

{
float jingdu =1E-5;//设置精度
float sum=1.0;
while(1)
{
 sum=(sum+fabs(x)/sum)/2.0;
  if(fabs(sum*sum-fabs(x))<=jingdu)
   break;
}
 return sum;
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有