问题:输入一个数,用牛顿迭代法求平方根?
#include <iostream> using namespace std; double EPS = 0.0001; //用于控制计算精度 int main() { //牛顿迭代法求输入数的平方根 double a; cin >> a; //输入a,要求a的平方根 if(a >= 0) { double x = a / 2, lastX = x + 1 + EPS; //确保能够进行一次迭代 while(x - lastX > EPS || lastX - x > EPS) { //只要精度未达到要求,就继续迭代 lastX = x; x = (x + a / x) / 2; } cout << x; } else cout << "It cant's be negative"; return 0; }
附上一个一重for循环求解阶乘的和问题。 1!+ 2!+ 3!+ 4!+ 5!+…+ n! = ???
#include <iostream> using namespace std; int main() { //一重循环解决阶乘的和 int n; cin >> n; int sum = 0; int factorial = 1; for(int i = 1; i <= n; i++) { factorial *= i; sum += factorial; } cout << sum << endl; return 0; }
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
QQ咨询|关于我们|Archiver|手机版|小黑屋|( 辽ICP备15012455号-4 ) Powered by 期权论坛 X3.2 © 2001-2016 期权工具网&期权论坛 Inc.
下载期权论坛手机APP