#斐波那契
int fic(int i )
{
if(i<2)
return i==0?0:1;
return fic(i-1)+fic(i-2);
}
int fic(int n )
{
if(n == 0)
return 1;
else return n*fic(n-1);
}
#反向输出任意长度字符串
void fic()
{
char c;
scanf("%c",&c);
if(c != '#') fic();
if(c != '#') printf("%c",c);
}
一、迭代实现
int search(int arr[],int n,int key)
{
int mid, low, high;
low = 0;
high = n-1;
while (low<=high) {
mid = (low + high)/2;
if (arr[mid] == key)
{
return mid;
}
if (arr[mid]<key) {
low = mid + 1;
}
if (arr[mid]>key) {
high = mid - 1;
}
}
// printf("%d,%d",low,high);
return -1;
}
int main()
{
int str[11] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
int n, addr;
printf("请输入待查找的关键字: ");
scanf("%d", &n);
addr = search(str, 11, n);
if( -1 != addr )
{
printf("查找成功,可喜可贺,可口可乐! 关键字 %d 所在的位置是: %d\n", n, addr);
}
else
{
printf("查找失败!\n");
}
return 0;
}
二、递归实现
int search(int arr[],int low,int high ,int key)
{
int mid;
if (low>high)
{
return -1;
}else
{
mid = (low + high)/2;
if (arr[mid] == key)
{
return mid;
}
if (arr[mid]<key) {
return search(arr, mid+1, high,key);
}
if (arr[mid]>key) {
return search(arr, low, mid - 1,key);
}
}
return -1;
}
int main()
{
int str[11] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
int n, addr;
printf("请输入待查找的关键字: ");
scanf("%d", &n);
addr = search(str, 0, 10, n);
if( -1 != addr )
{
printf("查找成功,关键字 %d 所在的位置是: %d\n", n, addr);
}
else
{
printf("查找失败!\n");
}
return 0;
}
#汉诺塔问题(精辟)
#include <stdio.h>
void mov(int n,char x,char y,char z)
{
if (1 == n)
{
printf("%c-->%c\n",x,z);
}else
{
mov(n-1, x, z, y);
printf("%c-->%c\n",x,z);
mov(n-1, y, x, z);
}
}
int main()
{
int n;
printf("请输入汉诺塔的层数:");
scanf("%d",&n);
printf("移动的步骤如下:\n");
mov(n, 'X', 'Y', 'Z');
return 0;
}