申明:写本篇文章的目的是为了方便自己使用,以下代码纯属自己编写,因为没有评测系统,因此无法保证正确性,若有人看到错误,请指正,谢谢。
题目1:猜数字的游戏,不太难的。题目:随即产生一个3位的正整数,让你进行猜数字,如果猜小了,输出:“猜小了,请继续”。如果猜大了,输出:“猜大了,请继续”。如果猜对了。输出:“恭喜你,猜对了”。不过最多只能猜10次,如果猜了10次还没有猜对,就退出程序,输出:“很遗憾”。
本题的难点在于,如何随机生成一个数字
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int key,i,x;
bool tag;
srand((unsigned)time(NULL));
key=rand()%1000;
tag=false;
for(i=0;i<10;i++)
{
scanf("%d",&x);
if(x==key)
{
printf("恭喜你,猜对了\n");
tag=true;
break;
}
if(x<key)
printf("你猜小了\n");
else if(x>key)printf("你猜大了\n");
}
if(!tag)
printf("很遗憾\n");
}
题目2:将字符串中的数字提取出来,并加和。如“No Signal ”,“123,and456”,“12, 123and124”
运行结果分别是0,579,259
#include<stdio.h>
#include<string.h>
#define MAX 1000
int main()
{
char s[MAX];
int i,sum,temp;
while(gets(s))
{
sum=0;
temp=0;
for(i=0;i<strlen(s);i++)
{
if('0'<=s[i]&&s[i]<='9')
temp=temp*10+s[i]-'0';
else
{
sum=sum+temp;
temp=0;
}
}
sum=sum+temp;
printf("%d\n",sum);
}
}
题目3:
处理一个文件 student.txt,然后将文本中的信息按总分排序,其中文本每列信息的意思是:
姓名 学号 英语 语文 数学 科学
张三 20100601 78 89 62 75
李四 20100602 78 54 98 86
王五 20100603 78 69 85 75
#include<stdio.h>
#include<algorithm>
using namespace std;
struct student
{
char name[20];
char id[20];
int chinese;
int math;
int english;
int science;
}stu[100];
bool cmp(student x,student y)
{
int sumx,sumy;
sumx=x.chinese+x.english+x.math+x.science;
sumy=y.chinese+y.english+y.math+y.science;
return sumx>sumy;
}
int main()
{
char str[20];
int cnt=0;
FILE *fpRead=fopen("student.txt","r");
if(fpRead==NULL)
return 0;
for(int i=0;i<6;i++)
{
fscanf(fpRead,"%s",&str);
printf("%s ",str);
}
printf("\n");
while(fscanf(fpRead,"%s",&stu[cnt].name)!=EOF)
{
fscanf(fpRead,"%s",&stu[cnt].id);
fscanf(fpRead,"%d",&stu[cnt].chinese);
fscanf(fpRead,"%d",&stu[cnt].math);
fscanf(fpRead,"%d",&stu[cnt].english);
fscanf(fpRead,"%d",&stu[cnt].science);
cnt++;
}
sort(stu,stu+cnt,cmp);
for(int i=0;i<cnt;i++)
printf("%s %s %d %d %d %d\n",stu[i].name,stu[i].id,stu[i].chinese,stu[i].math,stu[i].english,stu[i].science);
}