专业课真题复习(2019)

1.题目描述:
编写一个判断素数的函数,在主函数中输入一个整数,输出是否是素数的信息。

#include<stdio.h>
int isprime(int n)
{
    
    
	int i;
	for(i=2;i<=n/2;i++)
	{
    
    
		if(n%i==0)
		{
    
    
			return 0;
		}
	}
	return 1;
}
int main(void)
{
    
    
	int number;
	printf("请输入一个整数:\n");
	scanf("%d",&number);
	if(isprime(number))
	{
    
    
		printf("该数是一个素数,"); 
	}else{
    
    
		printf("该数不是一个素数");
	}
	return 0;
}

2.题目描述:
编写函数dayInMonth(int y,int m)方法。函数的功能是计算y年m月份包含的天数。

#include<stdio.h>
int dayInMonth(int y,int m)
{
    
    
	int monthtab[12]={
    
    31,28,31,30,31,30,31,31,30,31,30,31};
	if((y%4==0)||(y%100!=0&&y%4==0))
	{
    
    
		if(m==2)
		{
    
    
			return 29;
		}
	}
	return monthtab[m-1];
 } 
 int main(void)
 {
    
    
 	int year,month;
 	printf("请分别输入年月:\n");
 	scanf("%d%d",&year,&month);
 	printf("包含的天数为%d",dayInMonth(year,month));
 	return 0;
 }

3.题目描述:
13个人围成一圈,从第一个人开始顺序报号1,2,3。凡报到3者推出圈子。找出最后留在圈子中的人原来的序号。要求用链表处理。

#include<stdio.h>
struct people
{
    
    
	int no;
	int next;
}peoples[13];
int main()
{
    
    
	int i,j,count;
	int number=13;
	for(i=0;i<13;i++)
	{
    
    
		peoples[i].no=i+1;
		peoples[i].next=i+1;
		if(i==12)
		{
    
    
			peoples[i].next=0;
		}
	 } 
	 i=0;
	 count=0;
	 while(number>1)
	 {
    
    
	 	printf("number=%d\n",number);
	 	
	 	if(peoples[i].no!=0)
	 	{
    
    
	 		count++;
	 		
	 		if(count==3)
	 		{
    
    
	 			peoples[i].no=0;
	 			number--;
	 			count=0;
			 }
			 
		 }
		 i=peoples[i].next;
	 }
	 for(i=0;i<13;i++)
	 {
    
    
	 	printf("%d",peoples[i].no);
	 	if(peoples[i].no!=0)
	 	{
    
    
	 		printf("最后剩下的人的序号为%d",peoples[i].no);
		 }
	 }
	 return 0;
}

注意:1.书上给的是用静态链表做的,其他地方都是动态链表。
2. 指导最后一个的时候让他再指向头指针。

4.题目描述:
假设文件data.txt中一次读入各行文本,并把各行的文本的字符次序颠倒一下,即在原来k位置上的字符将出现在n-k+1的位置上,其中n是该行文本的长度(不包含最后的回车换行符或文件结束符),最后依次把各行颠倒了字符次序的文本保存到文件result.txt中。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void reverse(char *str)
{
    
    
	
	int end=strlen(str)-1;
	int start=0;
	char temp;
	while(start<=end)
	{
    
    
		temp=str[end];
		str[end]=str[start];
		str[start]=temp;
		start++;
		end--;
	}
}
int main(void)
{
    
    
	FILE *fd;
	FILE *fr;
	char arr[1000];
	int n;
	int len=0;
	if((fd=fopen("data.txt","r"))==NULL)
	{
    
    
		printf("can not open this file.");
		exit(0);
	}
	if((fr=fopen("result.txt","w"))==NULL)
	{
    
    
		printf("can not open this file.");
		exit(0);
	}
	while(!feof(fd))
	{
    
    
		fgets(arr,1000,fd);
		n=strlen(arr);
		if(arr[n-1]=='\n')
		{
    
    
			n-=1;
		}
		
	int end=n-1;
	int start=0;
	char temp;
	while(start<=end)
	{
    
    
		temp=arr[end];
		arr[end]=arr[start];
		arr[start]=temp;
		start++;
		end--;
	}
		fprintf(fr,"%s",arr);
	   
	}
	fclose(fd);
	fclose(fr);
	return 0;
}

注意:
1.题目中的条件是若干行,所以不能直接给出行数,但是fscanf()函数把空格也当成了文件结束的标志,教材中给出了这个思考问题。
2.要用feof()函数判断是不是文件末尾,每次都读出1000个字符,当遇到回车的时候,长度要-1.
strlen包括换行符,不包括结束符。

猜你喜欢

转载自blog.csdn.net/qq_44867340/article/details/121876659