计算机二级C常考题型归纳
数值处理题型
素数处理问题
整数拆分问题
#include<stdio.h>
int main()
{
int gw,sw,bw,qw,ww,n;
scanf("%d",&n);
gw=n%10;
sw=n%100/10;
bw=n%1000/100;
qw=n%10000/1000;
ww=n/10000;
printf("%d\n%d\n%d\n%d\n%d\n",gw,sw,bw,qw,ww);
}
公约数问题
(1)求m与n的公约数r
(2)若r=0,则n为最大公约数,算法结束
(3)将n的值放在m中,将r的值放在n中,转向执行第一步
#include<stdio.h>
int fun(int a,int b)
{
int r,t;
if(a<b)
{
t=a;
a=b;
b=t;
}
while(r!=0)
{
a=b;
b=r;
r=a%b;
}
return b;
}
int main()
{
printf("%d\n",fun(12,25));
}
数组处理问题
排序处理问题
冒泡排序
#include<stdio.h>
#include<stdlib.h>
#define N 100
bubble_sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
int main()
{
int i,n;
int a[N]={3,5,6,7,2,3,2,7,4,2};
for(i=0;i<N;i++)
a[i]=rand()%99;
bubble_sort(a,N);
for(i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
}
选择排序
选择最小的数到第一个位置,再选择剩下的数中的最小的数排在第二的位置…
矩阵最值处理问题 矩阵转置处理问题 字符串处理问题
//输入一串字符,输出其中大写字母
#include<stdio.h>
void main()
{
char s[20],*p="Hello";
char a;
puts(p);
p=s;
gets(s);
while(*p!='\0')
{
if('A'<=*p&&*p<='Z')
{
printf("%c\n",*p);
}
p++;
}
}
利用二维数组输入和输出多个字符串
#include<stdio.h>
void main()
{
char a[5][7];
int i;
for(i=0;i<5;i++)
gets(a[i]);
for(i=0;i<5;i++)
puts(a[i]);
}
字符串常用函数
//获取字符串长度
unsigned int strlen(const char *str);
//2复制字符串
char *strcpy(char *destination,const char *source);
//3.字符串连接
char *strcat(char *destination,const char *source);
//4.字符串比较,s1中的ASCII值大则返回1
int strcmp(const char *s1,const char *s2);
//5.字符串大小写转换
char *strupr(char *str);
判断回文单词
int Palindrome(const char *str)
{
int i=0,j=strlen(str)-1;
while(i<j)
{
while(str[i]==32)//如果是空格跳过
i++;
while(str[j]==32)
j--;
if(str[i]==str[j])
{
i++;
j--;
}else return 0;
}
return 1;
}
void main()
{
char a[5][7];
int i;
for(i=0;i<5;i++)
gets(a[i]);
for(i=0;i<5;i++)
if(Palindrome(a[i]))
puts(a[i]);
}
密码问题
int check(char *ps)
{
char password[]="PLWRV";
int i=0;
int flag=1;
for(;*ps!='\0'&&flag;ps++)
{
if(*ps>='a'&&*ps<'z')
*ps=*ps-32+2; //解密规则防止别人直接通过你的password里的内容就知道了你的密码,不过都是多余的,很容易解密
if(*ps!=password[i])
flag=0;
else
i++;
}
return flag;
}
void main()
{
char str[10];
int i=0;
printf("Input your password:\n");
while((str[i]=getchar())!='#')
i++;
str[i]='\0';
if(check(str))
printf("Pass!\n");
else
printf("ERROR!\n");
}