荔园在线
荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀
[回到开始]
[上一篇][下一篇]
发信人: huhaiming (一生只爱她), 信区: Program
标 题: 一些函数
发信站: 荔园晨风BBS站 (Mon Apr 19 22:54:02 2004), 站内信件
文件读写:
#include <stdio.h>
freopen(filename,"r",stdin);
freopen(filename,"w",stdout);
或者
#include <fstream.h>
#include <iostream.h>
ifstream cin(filename);
ofstream cout(filename);
质数判断:
IsPrime(int a)
{
int i;
for(i=2;i<=sqrt(a)+1;i++) if(a%i==0) return 0;
return 1;
}
求最大公约数(非递归)
int GCD(int a,int b)
{
while(b!=0)
{
x=a%b;
a=b;
b=x;
}
return a;
}
求最大公约数(递归)
int GCD(int p,int q)
{
if (q==0) return p;
return GCD(q,p%q);
}
求最小公倍数:
int LCM(int a,int b)
{
return a*b/GCD(a,b);
}
数制转换://实现1-61进制的转换 大小关系为 : 0-9,'a'-'z','A'-'Z'
char NToC(int num)
{
if(num<10) return num+'0';
else if(num<36) return num-10+'a';
else return num-36+'A';
}
int CToN(char c)
{
if(c>='0' && c<='9') return c-'0';
else if(c>='a' && c<='z') return 10+(c-'a');
else return 36+(c-'A');
}
void Trans(int srcweight,char * srcstr,int disweight,char * disstr)
{
int srcary[400],disary[400];
int slen=3;
int i,j;
int temp;
int jr=1;
slen=strlen(srcstr);
for(i=0;i<400;i++)
{
disary[i]=0;
srcary[i]=0;
}
for(i=0;i<slen;i++)
srcary[i]=CToN(srcstr[i]);
for(i=0;i<slen;i++)
{
j=0;
temp=srcary[i];
while(j<jr || temp!=0)
{
temp=disary[j]*srcweight+temp;
disary[j]=temp%disweight;
temp=temp/disweight;
j++;
}
jr=j;
}
jr--;
for(i=jr;i>=0;i--)
disstr[jr-i]=NToC(disary[i]);
disstr[jr-i]='\0';
}
数制转换:(2)
int translate(char *s,char *o)
{
int i,temp;
int len=strlen(s);//s的长度
int beginpos=0;//s的开始位置
int rlen=399;//o的结束位置
int mod;
//将字符转换成值
for(i=0;i<len;i++)
s[i]-=48;
while(beginpos!=len)//当s的所有位为零时结束循环
{
mod=0;
for(i=beginpos;i<len;i++)
{
temp=(s[i]+mod*10);
mod=temp%2;
s[i]=temp/2;
}//每一次循环的到o的一位,从后往前的填入o的数组里
while(s[beginpos]==0 && beginpos!=len)//判断s的高位是否为零
beginpos++;
o[rlen]=mod;//填入一位
rlen--;
}
return rle+1;//返回o的开始位置
}
快速排序:
int cmp(const void * p,const void * q)
{
return *(int *)p-*(int *)q;
}
void main()
{
int a[]={1,2,3,23,6,8,91,19,22};
int ac,i;
ac=sizeof(a)/sizeof(int);
qsort(a,ac,sizeof(int),cmp);
for(i=0;i<ac;i++) printf("%d ",a[i]);
}
在直线上:
float InLine(float ax,float ay,float bx,float by,float cx,float cy)
{
if((bx-ax)!=0)
{
k=(by-ay)/(bx-ax);
return by-cy-k*bx+k*cx;
}
else return cx-ax;
}
在圆内:
float InCircle(float cx,float cy, float radius,float ax,float ay)
{
return sqrt(pow((ax-cx),2)+pow((ay-cy),2))-radius;
}
筛法求素数
cosnt int MAXP=100000, NUMP=10000;
int notprime[MAXP];
int primes[NUMP];
int numprimes;
int prime()
{
int p,i,n;
primes[0]=2;
n=1;
for (p=3; p<MAXP; p+=2) {
if (!notprime[p]) {
for (i=2*p; i<MAXP; i+=p)
notprime[i]=1;
primes[n++]=p;
}
}
return n;
}
计算某数的各位之和
int sumdigits(int a)
{
int s;
s = 0;
while (a>0) {
s += a%10;
a = a/10;
}
return s;
}
floyd算法求最小路径(三个for循环,十分简单,略)
数组反转
void inverse(char s[M])
{
for(int j=strlen(s)-1,i=0;i<j;i++,j--) s[i]=s[i]+s[j]-(s[j]=s[i]);
}
自然数的拆分
//自然数的拆分
#include <iostream.h>
#include <iomanip.h>
void sum(int);
int a[20];
int i,j;
int main()
{
cout<<"Input n:";cin>>a[0];
j=0;
if(a[0]>1)
{
for(i=1;i<=a[0]/2;i++)
{
a[1]=i;
a[2]=a[0]-a[1];
sum(2);
}
}
cout<<"Program End.";
cin>>i;
return 0;
}
void sum(int kx)
{
int k,m,l;
j=j+1;
cout<<"Sum No."<<setw(3)<<j<<":"<<a[0]<<"=";
for(k=1;k<kx;k++)
cout<<a[k]<<"+";
cout<<a[kx]<<endl;
k=kx;l=a[k];
for(m=a[k-1];m<=l/2;m++)
{
a[k]=m;a[k+1]=l-m;
sum(k+1);
}
}
二进制转十进制
int oct_for_bin(char s[])
{
long total=0,;
int i, len=strlen(s);
for(i=len-1;i>=0;i--) if(s[i]=='1') total += (long)(pow(2,len-i-1+);
return total;
}
去掉字符串中的空格
char* TrimSpace(char *str)
{ for( char *s=str, *d=str; *d = *s++; d+=(*d==' ')?0:1); return str;
}
最小生成树 n为节点数,a[i][j]为邻接矩阵
初始化
for(i=0;i<26;i++)
for(j=0;j<26;j++)
if(i==j) a[i][j]=0;
else a[i][j]=1000000;
int spanning_tree()
{
int i,j,k=0,lowcost[1000],min,t,total=0;
for(i=1;i<n;i++) lowcost[i]=a[0][i];
lowcost[0]=-1;
for(i=1;i<n;i++){
min=1000000;
for(j=0;j<n;j++) if (lowcost[j]>0&&lowcost[j]<min)
min=lowcost[j],
t=j;
total+=min;
lowcost[t]=-1;
for(j=0;j<n;j++) if (a[t][j]<lowcost[j]) lowcost[j]=a[t][j];
}
return total;
}
求组合数C(n,m)
递归的方法
int combination(int m, int n)
{
if( m==0 ) return 0;
if( m<n ) return 0;
if(m<2*n) n=m-n;
if( n==0 ) return 1;
if( n==1 ) return m;
else return combination(m-1,n-1)+combination(m-1,n);
}
用定义求
int com(int m,int n)
{
int i,j,ret;
if( m==0 ) return 0;
if( m<n ) return 0;
if(m<2*n) n=m-n;
if( n==0 ) return 1;
if( n==1 ) return m;
for(i=ret=1,j=m; i<=n; i++,j--) ret *= j;
for(i=1;i<=n;i++) ret/=i;
return ret;
}
取天花函数
#define round(x) ((int)(x+0.5))
十进制与d进制之间的转换
void conver10-d (int N,int d) //十进制转成d进制
{
int x;
x = N>0 ? N : -N;
ClearStack(s); //置栈空
while(x)
{
Push(s,x%d);
x /= d;
}
if(N<0) printf("-");
while( !EmptyStack(s) )
{
x = Pop(s);
printf("%d",x);
}
}
图的遍历
求连通分量的算法
求无向图中各连通分量顶点集的算法//设无向图用邻接表存储
void ConnectComp( Vnode G[], int n )
{
bool visited[n];
int vi;
for( vi = 0; vi < n; vi++ ) visited[vi] = False;
for( vi = 0; vi < n; vi++ )
if( visited[vi] == False )
{
printf("\n Connected-Comp: ");
DFS( G, vi ); //BFS( G, vi ); 调用遍历算法DFS或者BFS
}
}
深度优先搜索
void DFS( Vnode G[], int v )
{
int u;
visit(G,v); //访问v顶点
u = firstadj( G,v ); //取v的第一邻接点u
while( u >= 0 )
{
if(visited[ u ] == False ) DFS( G, u ); //遍历子图
u = nextadj(G,v,u); //取v关于当前u的下一邻接点
}
}
任知两点,求所求点的交点,由两点式用线性代数解直线方程组求得( x , y )的
具体值
SOME h文件说明
bsearch 折半查找
调用格式 void *bsearch(const void *key,const void *base,size_t nelem,
size_t width,
int (* fcmp)(const void *,const void *));
包含文件 STDLIB.H
说 明 用折半查找算法搜索已知数组,减少找到匹配的比较次数。如果匹配变
量没有找到返回零;
否则返回匹配项的地址。当查找复制项数组时,匹配项不一定是数组的第一项
。像例程演示 的一样,bsearch()需要用户提供一个比较函数,类似于qsort()调
用的函数。向用户函数传递两个指针A和B,这两个指针指向要搜索数组中的元素。
用户函数必须在A<B时返回-1;
A==B时返回零;A>B时返回+1。
参数说明 const void *key指向要查找的关键字的指针,与数组中的项有相同的
数据类型。
const void *base指向按由低到高次序存放元素的数组的指针。
size_t nelem数组元素的个数。
size_t width数组中每一个元素的字节数。
int (* fcmp)(const void *,const void*)比较函数,参见例程。
参 见 bfind,lsearch,qsort
例 程 /* bsearch.cpp */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *array[]=
{
"Boston",
"Chicago",
"Cincinatti",
"Los Angeles",
"Miami",
"New York",
"Philadelphia"
};
#define WIDTH (sizeof(array[0])
#define NELEM (sizeof(array)/sizeof(array[0])
int Compare(const void *a,const void *b);
main()
{
char buffer[128]; //Input string buffer
char * *p; //Result of bsearch()
char *key; //Search key pointer
key=buffer;
printf("Enter search string:");
gets(buffer);
p=(char * *)bsearch(&key,array,NELEM,WIDTH,Compare);
if (p)
printf("Found %s\n",*p);
else
printf("%s not found\n",buffer);
return 0;
}
int Compare(const void *a,const void *b)
{
return stricmp(*(char * *)a,*(char * *)b);
}
clock 测定运行时间
调用格式 clock_t clock(void);
包含文件 TIME.H
说 明 返回从程序开始运行时经过的时间。系统没有内部时钟时返回-1。
clock_t类型在Borland
C++中有定义,但不一定在其它ANSIC编译器中也有定义,等同于long int。
参 见 gettime,time
例 程 /* clock.cpp */
#include <stdio.h>
#include <time.h>
#include <dos.h>
main()
{
clock_t t1,t2,t3;
t1=clock();
delay(500);
t2=clock();
t3=t2-t1;
printf("Clock ticks for 500ms delay==%lu\n",t3);
printf("500 mx delay in seconds==%f\n",t3/CLK_TCK);
return 0;
}
clrscr 清除屏幕
调用格式 void clrscr(void);
包含文件 CONIO.H
说 明 清除从光标位置到行尾(即到当前文本窗口的右边)的文本。
参 见 clreol,delline,gotoxy,window
例 程 /* clrscr.cpp */
#include <stdio.h>
#include <conio.h>
main()
{
int i,j;
clrscr(); //Erase display and "home" the
cursor
for (i=1;i<=24;i++)
for (j=1;j<=80;j++)
putch('x'); //Fill screen with x characters
gotoxy(10,10);
printf("\nPress Enter to end program");
while (getch()!=13)
clrscr(); //Clear screen again
gotoxy(1,25); //Put cursor on bottom line
return 0;
}
cos,cosl 计算余弦值
调用格式 double cos(double x);
long double cosl(long double x);
complex cos(complex x);
包含文件 MATH.H,COMPLEX.H
说 明 计算X的反余弦值。
参 见 acos,asin,atan,atan1,complex,matherr,sin,tan
例 程 /* cos.cpp */
#include <stdio.h>
#include <math.h>
#define V 0.25
main()
{
printf("Cosine of %lf==%lf\n",V,cosl(V));
return 0;
}
acos,acosl 计算反余弦
调用格式 double acos(double x);
long double acos(long double x);
complex acos(complex x);
包含文件 MATH.H,COMPLEX.H
说 明 计算X的反余弦值。
参 见 asin,atan,atan2,complex,cos,matherr,sin,tan
例 程 /* acos.cpp */
#include <stdio.h>
#include <math.h>
#define V 0.25
main()
{
printf("Arc cosine of %lf==%lf\n",V,acos(V));
return 0;
}
atan,atanl 计算反正切
调用格式 double atan(double x);
long doubel atan(long double x);
complex atan(complex x);
包含文件 MATH.H,COMPLEX.H
说 明 返回X的反正切值。
参 见 acos,asin,atan2,complex,cos,sin,tan
例 程 /* atan.cpp */
#include <stdio.h>
#include <math.h>
#define V 0.25
main()
{
printf("Arc tangent of %lf==%lf\n",V,atan(V));
return 0;
}
atan2,atan2l 计算y/x的反正切值
调用格式 double atan2(double y,double,y);
long doubel atan2(long double y,long double x);
包含文件 MATH.H
说 明 返回y/x的反正切值。
参 见 acos,asin,atan,cos,sin,tan
例 程 /* atan2.cpp */
#include <stdio.h>
#include <math.h>
#define X 80.0
#define Y 45.0
main()
{
double at2=atan2(Y,X);
printf("Arc tangent of %lf/%lf==%lf\n",Y,X,at2);
return 0;
}
atof ASCII码转换成浮点数
调用格式 double atod(const char *s);
包含文件 MATH.H
说 明 把字符串转换为double型的浮点数。返回浮点数,如果出错返回
+/-HUGE-VAL,并把
error设置成ERANGE。
参数说明 const char *s指向要转换的字符串的指针。
参 见 atoi,atol,_atold,cgets,gets,strtod
例 程 /* atof.cpp */
#include <stdio.h>
#include <math.h>
main()
{
char buffer[128];
double result;
printf("Enter double value to convert:");
gets(buffer);
result=atof(buffer);
printf("Result==%f\n",result);
return 0;
}
atoi ASCII码转换成整数
调用格式 int atoi(const char *s);
包含文件 STDLIB.H
说 明 把字符串转换为int型数。返回int值。如果不能转换返回零。
参数说明 const char *s指向要转换的字符串的指针。
参 见 atof,atol,cgets,gets,strtod
例 程 /* atoi.cpp */
#include <stdio.h>
#include <stdlib.h>
main()
{
char buffer[128];
int result;
printf("Enter integer value to convert:");
gets(buffer);
result=atoi(buffer);
printf("Result==%d\n",result);
return 0;
}
atol ASCII码转换成长整数
调用格式 long atol(const char *s);
包含文件 STDLIB.H
说 明 把字符串转换成long型数。返回long值。如果字符串不能转换返回零。
参数说明 const char *s指向要转换的指针。
参 见 atof,atoi,cgets,gets,strtod,strtol,strtonl
例 程 /* atol.cpp */
#include <stdio.h>
#include <stdlib.h>
main()
{
char buffer[128];
long result;
printf("Enter long value to convert:");
gets(buffer);
result=atol(buffer);
printf("Result==%ld\n",result);
return 0;
}
fabs,fabsl 返回浮点数绝对值
调用格式 double fabs(doubel x);
long double fabsl(long double x);
包含文件 MATH.H
说 明 返回浮点数X的绝对值(无符号)。
参数说明 double x任意double值。
long double x任意long double值。
参 见 abs,cabs,labs
例 程 /* fabs.cpp */
#include <stdio.h>
#include <math.h>
main()
{
double x=-123.321;
printf("%lf\n",x);
printf("%lf\n",fabs(x));
return 0;
}
floor,floorl 截尾函数
调用格式 double floor(double x);
long double floorl(long double x);
包含文件 MATH.H
说 明 返回不大于x的最大整数。换句话说,截尾x到可能的最大整数值。提供
两种形式:截尾double
时用floor(),截尾long double时用floorl()。
参 见 ceil,fmod,modf
例 程 /* floor.cpp */
#include <stdio.h>
#include <math.h>
main()
{
char buffer[128];
double d;
printf("Enter a floating point value:");
gets(buffer);
d=atof(buffer);
printf("Original value:%f\n",d);
printf("floor(value) :%f\n",floor(d));
return 0;
}
fmod,fmodl 取浮点数模余
调用格式 double fmod(double x,double y);
long double fmodl(long double x,long double y);
包含文件 MATH.H
说 明 返回x对y的模余,等于用x除y的余数。fmod()用于double值,fmodl()
用于long double值。
参 见 ceil,div,floor,fmod,modf
例 程 /* fmod.cpp */
#include <stdio.h>
#include <math.h>
main()
{
double v1=100,v2=17.5;
double result;
result=fmod(v1,v2);
printf("%lf,%lf)==%lf\n",v1,v2,result);
result 0;
}
freopen 连接流与新文件
调用格式 FILE *freopen(const char *filename,const char *mode,FILE
*stream);
包含文件 STDIO.H
说 明 关闭当前打开的文件流并把这个流与新命名的文件连接起来,常用于重
定向stdin,stdnt和
sederr流。
参数说明 const char *filename指向要与文件流连接的新文件名字符串的指针。
const char *mode指向fopen()的说明中列出的方式字符串的指针。打开文件的
方式。
FILE *stream与新命名的文件连接的打开的文件流。
参 见 fclose,fopen
例 程 /* freopen.cpp */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
FILE *outf;
char *fname=strdup(tmpnam(NULL));
//Redirect stderr to temporary output file
outf=freopen(fname,"w",stderr);
if (outf==NULL)
{
puts("Error opening temporary file");
exit(1);
}
fputs("Simulated error message\n",stderr);
fputs("written to file via stderr.\n",stderr);
fclose(outf);
printf("\nList file %s then delete.\n",fname);
return 0;
}
--
菩提本无树,明镜亦非台
本来无一物,何处惹尘埃
※ 修改:·huhaiming 於 Apr 22 16:27:01 修改本文·[FROM: 192.168.93.114]
※ 来源:·荔园晨风BBS站 bbs.szu.edu.cn·[FROM: 192.168.0.201]
[回到开始]
[上一篇][下一篇]
荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店