#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i ,sum=1;
double number=0.0;
for (i = 1; i <=10; i++)
{
sum = 1;
for (int n = 1; n <= i; n++)
sum *= n;
number += 1.0 / sum;
cout << number << endl; //输出number
if(fabs(number) < 1e-10)
break;
}
cout << “e的近似值为: “<<number+1.0<< endl;
return 0;
}
}
本人在if条件前输出了number,它的值变化:
条件是本人本人任意填的,不过小数精度总是2.71828,百思不得其解……………………………小白求指导惑。
#include<cmath>
using namespace std;
int main()
{
int i ,sum=1;
double number=0.0;
for (i = 1; i <=10; i++)
{
sum = 1;
for (int n = 1; n <= i; n++)
sum *= n;
number += 1.0 / sum;
cout << number << endl; //输出number
if(fabs(number) < 1e-10)
break;
}
cout << “e的近似值为: “<<number+1.0<< endl;
return 0;
}
}
本人在if条件前输出了number,它的值变化:
条件是本人本人任意填的,不过小数精度总是2.71828,百思不得其解……………………………小白求指导惑。
解决方案
60
可以这样:
#include<iostream> #include<cmath> using namespace std; int main() { int i ,sum=1; double number=0.0; for (i = 1; i <=10; i++) { sum = 1; for (int n = 1; n <= i; n++) sum *= n; number += 1.0 / sum; cout << fixed << setprecision(9) << number << endl; //小数输出9位 if(fabs(number) < 1e-10) break; } cout << "e的近似值为: "<<number+1.0<< endl; return 0; }
10