您的位置:首页 > 编程语言 > C语言/C++

递归练习(C语言)

2014-05-22 23:21 681 查看
本文地址:http://www.cnblogs.com/archimedes/p/recursive-practice.html,转载请注明源地址。

1、炮弹一样的球状物体,能够堆积成一个金字塔,在顶端有一个炮弹,它坐落在一个4个炮弹组成的层面上,而这4个炮弹又坐落在一个9个炮弹组成的层面上,以此类推。写一个递归函数CannonBall,这个函数把金字塔的高度作为参数,并且返回它所包括的炮弹数量。函数必须按照递归方式实现,不可以使用迭代结构,例如while或for。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

int *binary_search(int val, int array[], int n)
{
int m = n / 2;
if(n <= 0) return NULL;
if(val == array[m]) return array + m;
if(val < array[m]) return binary_search(val, array, m);
else return binary_search(val, array + m + 1, n - m - 1);
}

int main()
{
int n;
int *p;
int a[6] = {1,2,3,4,5,6};
while(~scanf("%d", &n)){
p = binary_search(n, a, 6);
if(p) {
printf("this number is in the array at position %d\n", p - a);
} else {
printf("this number is not in the array\n");
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: