5个常见C语言算法
十进制转换为二进制的递归程序
字符串逆置的递归程序
整数数位反序,例如12345->54321
四舍五入程序(考虑正负数)
二分法查找的递归函数
#include
#include
#include
//十进制转换为二进制的递归程序
voidDecimalToBinary(int n)
{
if(n<=0)
{
printf("0"); return;
if(n==1)
{
printf("1"); return;
}
else
{
DecimalToBinary((int)n/2);
printf("%d",n%2);
return;
}
}
//字符串逆置的递归程序
voidInverseString(char *s,int n)
{
if(n<=1) return;
else
{
char ch;
ch= s[0];
s[0]= s[n-1];
s[n-1] = ch;
InverseString(s+1,n-2);
}
}
//整数数位反序12345->54321
intInverseIntBit(int n)
{
int sum = 0;
while(n)
{
sum = sum * 10 + n % 10;
n /= 10;
}
return sum;
}
//四舍五入程序(考虑正负数):
intRoundDouble(double d)
{
int sign = 0;
sign = (d>0)?1:-1;
double td = d + sign * 0.5;
return (int)td;
}
//二分法查找的递归函数
intBinarySearch(int key,int a[],int low,int high)
{
if(low>high) return 0;
int mid = (low+high)/2;
if(a[mid]>key) return BinarySearch(key,a,low+1,mid-1);
else if(a[mid]return BinarySearch(key,a,mid+1,high-1);
else return 1;
}
voidmain()
{
printf("/nDecimal To Binary(224) = ");
DecimalToBinary(224);
char a[27] = "abcdefghijklmnopqrstuvwxyz";
InverseString(a,26);//这里必须考虑后面的'/0'
printf("/nString Inverse(abcdefghijklmnopqrstuvwxyz) = %s/n",a);
int t = InverseIntBit(123456);
printf("/nInt Inverse 123456 = %d/n",t);
int rd1 = RoundDouble(1.4);
int rd2 = RoundDouble(1.5);
int rd3 = RoundDouble(-1.4);
int rd4 = RoundDouble(-1.5);
printf("/nround(1.4)=%d round(1.5)=%d round(-1.4)=%d round(-1.5)=%d/n",rd1,rd2,rd3,rd4);
int aa[10] = {0,1,2,3,4,5,6,7,8,9};
if(1==BinarySearch(7,aa,0,9)) printf("/nI Find 7 /n");
else printf("/nI Cannot Find 7/n");
if(1==BinarySearch(17,aa,0,9)) printf("/nI Find 17/n");
else printf("/nI Cannot Find 17/n");
getch();
}
结果:
{
printf("0"); return;
}
printf("0"); return;
}
}