C语言求一个数的平方根

本文介绍了一个使用C语言实现的求平方根算法,通过迭代逼近的方法计算任意正数的平方根,直到达到预设的精度。算法首先让用户输入一个数值,然后利用牛顿迭代法进行计算,直到误差小于0.00001为止。

include<stdio.h>

#include<math.h>

void main()

{

float a,x1=1,x2,t=0;                   (赋值)

printf("请输入一个数:\n");

scanf("%f",&a);

 x2=(1/(2.0))*(x1+a/x1);

    while(fabs(x2-t)>0.00001)            (精确度)

{  

  x2=(1/(2.0))*(x1+a/x1);

  t=x1;                           (相互记录值)

  x1=x2;

}

printf("%.2f的平方根为:%.5f\n",a,x2);

}

转载于:https://www.cnblogs.com/Latent-Truth/p/3471854.html

在C语言中,某个平方根有多种实现方法,具体如下: ### 使用学库中的`sqrt()`函 C语言学库中提供了`sqrt()`函,可直接用于计算平方根。以下是示例代码: ```c #include <stdio.h> #include <math.h> int main() { double number, squareRoot; printf("请输入一个值:"); scanf("%lf", &number); // 使用sqrt()函计算平方根 squareRoot = sqrt(number); printf("平方根为:%.2lf\n", squareRoot); return 0; } ``` 此方法简洁方便,适用于大多场景,不过需要包含`<math.h>`头文件。 ### 通过迭代法计算平方根可通过计算一系列近似值来获得,每个近似值都比前一个更接近准确值。第一个近似值设为1,后续近似值通过特定公式计算。当某个近似值与前一个近似值相等时,程序停止计算。代码示例如下: ```c #include <stdio.h> #include <stdlib.h> int main() { float new_guess; float last_guess; float number; // 催促用户输入,读取据并对它进行检查 printf("Enter a number: " ); scanf("%f", &number ); if( number < 0 ) { printf("Cannot compute the square root of a " "negative number! \n"); return EXIT_FAILURE; } // 计算平方根的近似值,直到它的值不再变化 new_guess = 1; do { last_guess = new_guess; new_guess = ( last_guess + number / last_guess ) / 2; printf ("%.15e\n", new_guess ); } while( new_guess != last_guess ); // 打印结果 printf ("Square root of %g is %g\n", number, new_guess ); return EXIT_SUCCESS; } ``` 该方法要对负值输入进行检查,且使用浮点变量存储近似值。 ### 牛顿迭代法 设置`ϵ`来控制精度,判断所`a`是否为正。若`a > 0`,可平方根;若`a < 0`,不可平方根。代码如下: ```c #include <stdio.h> int main() { double eps = 0.001; // epsillon用以控制计算精度:若找到的长宽之差小于0.001,则认为足够精确 double a; printf("请输入一个: "); scanf("%lf", &a); if (a >= 0) { // 若a为正,可平方根 double x = a / 2, y = a / x; // 猜测矩形的长、宽,并初始化 while (x - y > eps || y - x > eps) { // 只要精度未达要,长宽不够接近,就继续迭代 y = a / x; // 每次迭代先用原来的长x更新宽y x = (x + y) / 2; // 再更新长x(公式) } printf("平方根为: %lf\n", x); // 若|x - y| < eps,迭代完毕,输出精确根 } else { // 若a为负,不可平方根 printf("It can't be negative.\n"); } return 0; } ``` 此方法通过不断迭代使结果逼近准确值,`ϵ`的值可根据需调整以控制精度[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值