申明:写本篇文章的目的是为了方便自己使用,以下代码纯属自己编写,因为没有评测系统,因此无法保证正确性,若有人看到错误,请指正,谢谢。
题目:1:判断一个数N是否是素数,是的话输出“YES”,否则输出“NO”。(判断2-sqrt(N)是否存在N的因子即可)
输入:
1000000007
100
输出:
YES
NO
#include<stdio.h>
#include<string.h>
#define MAX 1000000
bool p[MAX];
bool is_prime()
{
memset(p,true,sizeof(p));
for(int i=2;i<MAX;i++)
{
if(p[i])//如果是素数那么他的倍数必然不是素数
for(int j=2*i;j<MAX;j+=i)
p[j]=false;
}
p[0]=false;p[1]=false;
}
int main()
{
int n;
is_prime();
while(scanf("%d",&n)!=EOF)
{
if(p[n])
printf("YES\n");
else printf("NO\n");
}
}
题目2:在一个二维平面内有n个点,每个点坐标为(x,y),求最近的两点的距离。(暴力求解即可)
输入:
5
1 2
100 200
1000 2000
1000 1
1 3
输出:
1
#include<stdio.h>
#include<math.h>
#define MAX 100000
int main()
{
int n,min=-1,temp;//min=-1说明还没有过最小值
int x[MAX],y[MAX];
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d %d",&x[i],&y[i]);
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
temp=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
if(temp<min||min==-1)
min=temp;
}
printf("%d\n",min);
}
题目3:有一个文件记录了学生期末考试的几门成绩和学号,求出这几门课程的平均分和总分,并按照总分排序,从高到底,如果成绩相同,按照学号从小到大的顺序。(文件要用c语言的读写操作(读写操作戳这里),结构体排序可做)
为了解决这一道题目,我们首先要解决数据问题,因为这道题的数据是有关文件的读写的,我们可以自己创建一个文件,类似于下图:
数据如下:以tab作为间隔符
姓名 | 学号 | 语文 | 数学 | 英语 |
---|---|---|---|---|
A | 1 | 20 | 40 | 40 |
B | 2 | 66 | 39 | 68 |
C | 3 | 99 | 5 | 5 |
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct student{
char name[20];
int id;
int chinese;
int math;
int english;
int sum;
}stu[101];
bool cmp(student x,student y)
{
if(x.sum!=y.sum)
return x.sum>y.sum;
else return x.id<y.id;
}
int main()
{
FILE *fpRead=fopen("data.txt","r");
if(fpRead==NULL)
return 0;
char str[20];
int cnt;
for(int i=0;i<5;i++)
{
fscanf(fpRead,"%s",str);
printf("%s ",str);
}
printf("\n");
cnt=0;
while(fscanf(fpRead,"%s",&str)!=EOF)
{
strcpy(stu[cnt].name,str);
fscanf(fpRead,"%d",&stu[cnt].id);
fscanf(fpRead,"%d",&stu[cnt].chinese);
fscanf(fpRead,"%d",&stu[cnt].math);
fscanf(fpRead,"%d",&stu[cnt].english);
stu[cnt].sum=stu[cnt].chinese+stu[cnt].math+stu[cnt].english;
cnt++;
}
sort(stu,stu+cnt,cmp);
for(int i=0;i<cnt;i++)
printf("%s %d %d %d %d\n",stu[i].name,stu[i].id,stu[i].chinese,stu[i].math,stu[i].english);
getchar();//等待
}
题目4:有一个由数字组成的二维矩阵,大小为NM;还有一个大小为nm小二维矩阵,想象将小二维矩阵上面(小矩阵左上角位置和大矩阵某个位置对应放弃),在不同的位置,这两个二维矩阵对应位置的数字绝对值之差和一般是不同的,求这个最小绝对值之差的和,并求出对应的大矩阵位置。(暴力求解,枚举大矩阵的位置即可)
输入4 4
1 2 3 4
4 5 6 8
1 2 3 4
5 6 7 8
2 2
2 2
4 5
输出:最小距离为0,对应的坐标起始点(1,1)、(3,1)。