您的位置:首页 > 职场人生

经典面试题 之 递归调用 几个经典示例

2013-07-17 17:00 274 查看
1、 求算1-100  
#include <iostream>
int fun(int n, int &sum)  
{  
   n && fun(n - 1, sum);  
   return (sum += n);  
}  
int main()  
{  
int sum = 0;  
int n = 100;  
printf("1+2+3+...+n=%d\n", fun(n, sum));  
return 0;  
system("pause");
}


2、 求算 数列 1,1,2,3,5,。。。。第二十个数的 值

#include<iostream>
using namespace  std;

int  fun(int  n)
{
	if(n == 1 || n == 2)
		return  1;
	
	return  (fun(n-1) + fun(n-2));
}

int  main()
{
	int num = 20;
	printf("num=%d\n",  fun(num));
	system("pause");
	return 0;
}


3、 求文件夹的大小

#include <stdio.h>     
#include <dirent.h>  
#include <sys/stat.h>    
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
static int
mc_get_stat(char *filename, struct stat *stbuf)
{
    return stat(filename, stbuf);        /* 跟随符号链接 */
} 

/* 遍历目录或者文件, 返回整个目录或者文件的大小 */
static blkcnt_t 
mc_do_du(char *filename, int *len)
{
    DIR    *dp;
    char    name[256];
    struct     dirent    *p;
    blkcnt_t     n;
    struct stat    stbuf;
    n = 0;
    if(mc_get_stat(filename, &stbuf) == -1){
        fprintf(stderr, "%s cannot access \n", filename);
        return n;
    }	 
    if(S_ISDIR(stbuf.st_mode)){
        dp = opendir(filename);
        while(p = readdir(dp)){
            if(!strcmp(".", p->d_name) || !strcmp("..", p->d_name))
                continue; 
            else{    /* 文件名超过255个字符时行为未定义 */
                strcpy(name, filename);
                strcat(name, "/");
                strcat(name, p->d_name); 
                n = mc_do_du(name, len);
            }
        }    
        closedir(dp);    
    }
    return  *len += stbuf.st_size; 
}    

int main()
{
  int len =0, len1=0;
   len1 =  mc_do_du("/usr/local/bin/qq", &len);	
	printf("len1 =%d, len=%d\n", len1, len);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: