zoukankan      html  css  js  c++  java
  • u Calculate e

    很久没有做算法题了,其实做一些算法题对自己也是有很大的帮助的,至少再闲暇无聊的时候,可以消磨时间也是一件很不错的休闲娱乐活动。下面是一道简单题,热身用的,呵呵,以后有空我要多做做这类算法题了,一方面娱乐,一方面也是扩展自己思维的一个很不错的选择。

    原题如下:

    ZOJ Problem Set - 1113

    u Calculate e


    Time Limit: 1 Second      Memory Limit: 32768 KB


    Background
    A simple mathematical formula for e is

    where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.

    Output
    Output the approximations of e generated by the above formula for the values of n from 0 to 9. The beginning of your output should appear similar to that shown below.

    Example

    Output

    n e
    - -----------
    0 1
    1 2
    2 2.5
    3 2.666666667
    4 2.708333333

    Source: Greater New York 2000

    题目很简单,我不做太多的分析了。

    在看到后面的这个格式输出的时候,第一时间我想到的就是用C来做,printf这个函数,对这种格式控制还是很犀利的。当然也可以利用iomanip这个库中的函数,用C++来完成这个控制,我是用printf作的。看到前三个输出是一个有限小数,而且位数没有后面的多,于是我考虑直接先输出前面的内容,再计算后面的内容,解法如下:

      1: #include<stdio.h>
    
      2: void main()
    
      3: {
    
      4: 	double arr[10] = {1};
    
      5: 	int i = 1,j = 3;
    
      6: 	while(i < 10)
    
      7: 	{
    
      8: 		arr[i] = i * arr[i - 1];
    
      9: 		i++;
    
     10: 	}
    
     11: 	printf("n e\n");
    
     12: 	printf("- -----------\n");
    
     13: 	printf("0 1\n");
    
     14: 	printf("1 2\n");
    
     15: 	printf("2 2.5\n");
    
     16: 	double result = 2.5;
    
     17: 	while(j < 10)
    
     18: 	{
    
     19: 		result = result + 1/arr[j];
    
     20: 		printf("%d %11.9f\n",j,result);
    
     21: 		j++;
    
     22: 	}
    
     23: } 
  • 相关阅读:
    loj 1257 (求树上每一个点到树上另一个点的最长距离)
    loj 1032 数位dp
    loj 1030概率dp
    loj1011 状态压缩
    java大数取模
    求阶乘的位数
    loj 1426(dfs + bfs)
    携程greenlet模块使用
    如何让socket编程非阻塞?
    分别用request和socket给百多发送请求
  • 原文地址:https://www.cnblogs.com/malloc/p/1844500.html
Copyright © 2011-2022 走看看