解题思路:
牛顿迭代法求平方根: 假设a。欲求a的平方根,首先猜测一个值X1=a/2,然后根据迭代公式 X(n+1)=(Xn+a/Xn)/2, 算出X2,再将X2代公式的右边算出X3等等,直到连续两次算出的Xn和X(n+1)的差的绝对值小于 某个值,即认为找到了精确的平方根 例: 假设a=4, x1=4/2=2; x2=(2+4/2)/2=2 2-2<0.00001 ==>平方根=2 假设a=9, x1=9/2=4.5; x2=(4.5+9/4.5)/2=3.25 4.5-3.25>0.00001 x3=(3.25+9/3.25)/2=3.00962 3.25-3.00962>0.00001 x4=(3.00962+9/3.00962)/2=3.00002 3.00962-3.00002>0.00001 .... ==>平方根=3 利用循环,即可解题
注意事项:
理解题意,善用循环,绝对值得差小于0.00001
参考代码:
#include"iostream" #include"cmath" //调用求绝对值函数 fabs(); #include"cstdio" //使用格式化输出printf(); using namespace std; int main(){ double x,b,c; cin>>x; b=x/2; while(1){ c=(b+x/b)/2; if(fabs(c-b)<0.00001) break; b=c; } printf("%.3lf\n",c); return 0; }
0.0分
62 人评分
//输出n的所有因子 #include <iostream> #include <iomanip> using namespace std; int main() { double N ; double a , b ; cin>>N ; //16 a = N / 2 ; //8 b = ( a + (N/a) ) / 2 ; // 8+2 / 2 = 5 ; while((a-b)>0.00001) { //a - b > 0.00001 a = b ; b = ( b + N/b ) / 2 ; } cout<<fixed<<setprecision(3)<<b; return 0; }
#include<bits/stdc++.h> #include<cmath> using namespace std; int main(){ double a,b,c; cin >>a; b=a/2; while (1){ c=(b+a/b)/2; if(fabs(c-b)<0.00001) break; b=c; } cout <<fixed<<setprecision(3)<<c<<endl; return 0; }
#include<stdio.h> int main() { float s,a; scanf("%f",&a); s=a/2.0; while(1){ if((s+a/s)/2.0-s<0.00001){ printf("%0.3f\n",(s+a/s)/2.0);break; } s=(s+a/s)/2.0; } return 0; }
为什么 fabs(b-a)<0.00001 必须要在if里 while(fabs(b-a)>0.00001) 为什么会错?
printf基础练习2 (C语言代码)浏览:320 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:485 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:674 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:551 |
C语言程序设计教程(第三版)课后习题9.2 (C语言代码)浏览:572 |
C语言训练-亲密数 (C语言代码)浏览:695 |
1009题解浏览:799 |
A+B for Input-Output Practice (C语言代码)浏览:503 |
C二级辅导-等差数列 (C语言代码)浏览:803 |
1197求助浏览:666 |
Joker 2022-10-27 10:15:28 |
随便假设一种关系,然后带入计算