初学C语言常用简单程序代码.doc
文本预览下载声明
初学C语言常用简单程序代码
素数的筛选
#include stdio.h
#include math.h
#define N 1000
int main(int argc, char* argv[])
{
int i,j,num[N];
for(i=0;iN;i++)
num[i]=i+1;
for(i=1;i(int)sqrt((double)N);i++)
{
if(num[i])
{
for(j=i+1;jN;j++)
{
if(num[j])
if(num[j]%num[i]==0)
num[j]=0;
}
}
}
for(i=1;iN;i++)
if(num[i])
printf( %d,num[i]);
return 0;
}
输出时分秒
#include stdio.h
main()
{
int x,s,t,d;
scanf(%d,x);
s=x%60;
t=(x/60)%60;
d=(x/60)/60;
printf(%d时%d分%d秒,d,t,s);
}
三个数的交换
#include stdio.h
void main()
{
int a,b,c,t;
scanf(%d%d%d,a,b,c);
printf(The original number:a=%d,b=%d,c=%d\n,a,b,c);
t=a,a=b,b=t;
t=a,a=c,c=t;
printf(after swap:a=%d,b=%d,c=%d,a,b,c);
}
switch语句的运用
#include stdio.h
main()
{
int a,m;
printf(please input a number:);
scanf(%d,a);
switch(a/10)
{
case 10:
case 9: m=5; break;
case 8: m=4; break;
case 7:m=3; break;
case 6:m=2; break;
default:m=1;
}
printf(m=%d,m);
}
判断奇数和偶数
#include stdio.h
main()
{
int x;
printf(Please input a number: );
scanf(%d,x);
if(x%2==0)
printf(this is a oushu!);
else
printf(this is a jishu!);
}
小写改大写,若是大写则不变
include stdio.h
main()
{
char c1,c2;
printf(Input a letter\n);
scanf(%c,c1);
c2=(a=c1c1=z)?(c1-a+A):c1;
printf(%c,c2);
getchar();
return 0;
}
输入一个数,输出这个数是几位数
#include stdio.h
main()
{
int x,n;
printf(please input a number:);
scanf(%d,x);
n=0;
while(x!=0)
{
x=x/10;
n++;
}
printf(%d,n);
}
输入一个数,判断它是几位数,然后逆序输出
#includestdio.h
int main()
{
int num;
int len = 0;
int temp =0;
printf(Please input a number:\n);
scanf(%d,num);
while((num % 10)!=0)
{
temp = temp*10+(num%10);
len++;
num = num/10;
}
printf(length = %d\n,len);
printf(Reverse is %d, temp);
}
打印水仙花数
#include stdio.h
main()
{
int x, a,b,c;
for(x=100;x=999;x++)
{
a=x%10;
b=(x/10)%10;
c=x/100;
if(x==a*a*a+b*b*b+c*c*c)
{
printf(%5d,x);
}
}
显示全部