刘汝佳/算法竞赛入门经典第三章数组和字符串-上
- 习题3-1 分数统计
- 输入一些学生的分数,那个分数出现的次数最多?如果有多个并列,从小到大输出.
- #include<stdio.h>
- #include <string.h>
- int main()
- {
- int a[10],b[10],count[10];
- int max;
- memset(count,0,sizeof(count));
- int i,j;
- printf("请输入10个学生的分数\n");
- for(i=0;i<10;i++)
- {
- scanf("%d",&a[i]);
- b[i]=a[i];
- }
- for(j=0;j<10;j++)
- {
- for(i=0;i<10;i++)
- {
- if(a[j]==b[i])
- {
- count[j]+=1;
- }
- }
- //printf("第%d个数%d出现的次数为%d\n",j+1,a[j],count[j]);
- }
- max=count[0];
- for(i=1;i<10;i++)
- {
- if(count[i]>=max)
- {
- max=count[i];
- }
- }
- int temp[10];
- for(i=0;i<10;i++)
- {
- temp[i]=-1;
- }
- int k=0;
- for(i=0;i<10;i++)
- {
- if(max==count[i])
- {
- temp[k++]=a[i];
- }
- }
- for(i=0;i<k-1;i++)
- {
- //排序
- for(j=0;j<k-1-i;j++)
- {
- if(temp[j]>temp[j+1])
- {
- int t=temp[j+1];
- temp[j+1]=temp[j];
- temp[j]=t;
- }
- }
- }
- for(i=0;i<k;i++)
- printf("%d出现的次数最多,次数为%d\n",temp[i],max);
- return 0;
- }
- 运行结果:
- 习题3-2单词的长度
- 输入若干单词,输出它们的平均长度,单词只包括大小写字母,用一个或多个空格隔开
- #include<stdio.h>
- #include <string.h>
- #include<ctype.h>
- #define MAXN 1000+10
- char buf[MAXN],s[MAXN];
- int p[MAXN];
- int main()
- {
- int i,j,m=1,n,k=0;
- int count=0;
- float averlength;
- fgets(buf,sizeof(s),stdin);//从标准输入设备(就是键盘)读入一串字符,包括空白等符号在内。读入到 字符数组 buf 里,读入最大长度为 s[MAXN]
- n=strlen(buf);
- // printf("n=%d\n",n);
- for(i=0;i<n;i++)
- {
- if(!isalpha(buf[i]))//判断是否为字母
- {
- //printf("%d ",i);
- p[k++]=i;
- count+=1;
- }
- }
- // printf("count=%d\n",count);
- // printf("%d\n",k);
- for(j=0;j<k;j++)
- {
- if((p[j+1]-p[j])>1)
- {
- m+=1;
- }
- }
- printf("单词个数=%d\n ",m);
- printf("所有单词的总长度=%d\n ",n-count);
- averlength=(float)(n-count)/m;
- printf("平均长度=%.3f\n",averlength);
- return 0;
- }
- 习题3-3乘积的末三位
- 输入若干整数(正负或零),输出它们乘积的末三位.这些整数中会混入一些由大写字母组成的字符串,你的程序应当忽略它们.
- #include<string.h>
- #include<stdio.h>
- int main(){
- char c;
- int s=1;
- int t=1;
- int mark=0;
- while((c=getchar())!=EOF&&c!='\n'){
- if(c>='0'&&c<='9'){
- if(mark!=0){
- t=t*10+(c-'0');
- }
- else
- t=(c-'0');
- mark++;
- }
- else if(c==' '){
- t=t%1000;
- if(mark!=0)
- s=s*t;
- mark=0;
- t=0;
- s=s%1000;
- }
- }
- if(mark!=0)
- s=s*t;
- s=s%1000;
- printf("%ld\n",s);
- return 0;
- }
- 习题3-4计算器
- 编写程序,输入一行恰好包含一个加号,减号,或乘号的表达式,输出他们的值,运算符为二元运算符,运算数不超过100的非负整数.运算数和运算符可以紧挨着,也可以用一个或多个空格隔开
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAXN 100
- char a[MAXN];
- int main(int argc, char *argv[])
- {
- int i, n, x = 0, y = 0, middle;
- while(fgets(a, sizeof(a), stdin))
- {
- n = strlen(a);
- for(i = 0; i < n-1; i++)
- {
- if(a[i] == '+' || a[i] == '-' || a[i] == '*')
- middle = i;
- }
- for(i = 0; i < middle; i++)
- {
- if(a[i] == ' ') continue;
- x = x*10 + a[i] - '0';
- }
- for(i = middle+1; i < n-1; i++ )
- {
- if(a[i] == ' ') continue;
- y = y*10 + a[i] - '0';
- }
- switch(a[middle])
- {
- case '+':
- printf("%d\n", x+y);break;
- case '-':
- printf("%d\n", x-y);break;
- case '*':
- printf("%d\n", x*y);break;
- }
- x = 0;
- y = 0;
- }
- system("PAUSE");
- return 0;
- }
- 未完持续......