C习题一道!越写越头晕~

来源:百度知道 编辑:UC知道 时间:2024/05/23 18:42:44
按给定近似公式计算e=1+1/1!+1/2!+1/3!+…+1/n!+…,当1/n!的值小于10的-7次方时结束。(!表阶乘,如4!=4*3*2;5!=5*4*3*2)

#include<iostream>
using namespace std;

void main() {
int x = 1;
long y = 1;
double s = 1;
while(y <= 10000000) {
s += 1./y;
y *= ++x;
}
cout<<s<<endl;
}

#include<stdio.h>

int main()
{
double n=1;
int k=1;
int jiecheng=1;

while( (1.0/jiecheng)>0.00000001 )
{
k++;
jiecheng=jiecheng*k;
n=n+1/jiecheng;
}
printf("e=%d\n",n);
return 0;
}
三楼说得对,是要加个点

真不知道楼上的有没有上机调试过,现修改如下:
#include<stdio.h>

main()
{
double n=1;
int k=1;
double jiecheng=1;

while( (1.0/jiecheng)>0.0000001 )
{
k++;
jiecheng=jiecheng*k;
n=n+1.0/jiecheng;
}
printf("e=%f\n",n);
}

记住,如果jiecheng为2,1/jiecheng=0,1.0