|
发表于 2023-12-24 22:49:03
|
显示全部楼层
本帖最后由 jackz007 于 2023-12-24 23:52 编辑
- while (fx > 1e-15 || fx < -1e-15)
- {
- int base = 1 ; // 不可以在循环体内定义这个变量 base, 因为,每次循环到这里,变量 base 都会被重新定义,其值都将被初始化为 1
- . . . . . .
- base = -base ; // 如果选择在循环体内定义变量 base,那么,这一句代码就会完全失效。
-
复制代码
【版本1】:使用 pow() 函数
- #include<iostream>
- #include<cmath>
- using namespace std ;
- double arctan(double x)
- {
- int i , base ;
- double d , sum ;
- for(i = base = 1 , sum = 0 ;; i += 2 , base = -base) {
- d = pow(x , i) / i ;
- if(d > 1e-15) sum += base * d ;
- else break ;
- }
- return sum ;
- }
- int main()
- {
- double a , b , c ;
- b = 16 * arctan(1 / 5.0) ;
- c = 4 * arctan(1 / 239.0) ;
- a = b - c ;
- cout << arctan(1) << endl ;
- cout << a << endl ;
- }
复制代码
【版本2】:不使用 pow() 函数
- #include<iostream>
- using namespace std ;
- double arctan(double x)
- {
- int i , base ;
- double d , e , sum ;
- for(d = e = sum = x , base = -1 , i = 3 ;; i += 2 , base = -base) {
- e = e * x * x ; // e = pow(x , i)
- d = e / i ;
- if(d > 1e-15) sum += base * d ;
- else break ;
- }
- return sum ;
- }
- int main()
- {
- double a , b , c ;
- b = 16 * arctan(1 / 5.0) ;
- c = 4 * arctan(1 / 239.0) ;
- a = b - c ;
- cout << arctan(1) << endl ;
- cout << a << endl ;
- }
复制代码 |
|