1.输出S的值,精度1e-6
#include <stdio.h>
int main() {
int i=1;
double flag=1.0/(2*i-1)*2*i/(2*i-1);
double sum=0;
while(flag>1e-6) {
sum+=flag;
i++;
flag=1.0/(2*i-1)*2*i/(2*i-1);
}
printf("%lf",sum);
}
2.编写函数,对n个字符串按字典顺序排序限定函数名void sort(char st[ ][10], int n)
#include <stdio.h>
void strcpy(char *str1,char *str2) {
int i=0;
while(str1[i]!='\0') {
str2[i]=str1[i];
i++;
}
str2[i]='\0';
}
int strcmp(char *str1,char *str2) {
int i=0;
while(str1[i]!='\0'&&str2[i]!='\0') {
if(str1[i]>str2[i])
return 1;
else if(str1[i]<str2[i])
return -1;
else
i++;
}
if(str1[i]=='\0'&&str2[i]=='\0')
return 0;
else if (str1[i]=='\0')
return -1;
else
return 1;
}
void sort(char st[][10],int n) {
char temp[10];
for(int i=0; i<n-1; i++)
for(int j=0; j<n-i-1; j++)
if(strcmp(st[j],st[j+1])==1) {
strcpy(st[j],temp);
strcpy(st[j+1],st[j]);
strcpy(temp,st[j+1]);
}
}
int main() {
char st[][10] = {"hello", "world", "python", "C", "java", "R"};
int n = 6;
sort(st, n);
for (int i = 0; i < n; i++)
printf("%s ", st[i]);
printf("\n");
return 0;
}
3.编写递归函数,实现对有序数组的二分查找
#include <stdio.h>
int search(int *a,int left,int right,int key) {
while(left<=right) {
int mid=(left+right)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
return (a,mid+1,right,key);
return(a,left,mid-1,key);
}
return -1;
}
4.成绩信息包含:姓名,学号,讨论成绩,报告成绩,测试成绩五项信息,规定:
实验成绩 = 讨论成绩(20%)+报告成绩(20%)+测试成绩 (60%)
1)创建结点类型;
2)假如所有信息都存储在文件2018.txt中,创建链表;
3)对题中的里链表按实验成绩,从高到低排序
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char name[20];
int num;
int repscore;
int expscore;
int testscore;
struct node *next;
} node;
struct node *create() {
FILE *file;
if((file=fopen("2018.txt","r"))==NULL) {
printf("open error");
exit(0);
}
struct node *head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
struct node *p;
while(!feof(file)) {
p=(struct node *)malloc(sizeof(struct node));
fscanf(file,"%s %d %d %d %d",&p->name,&p->num,&p->repscore,&p->expscore,&p->testscore);
p->next=head->next;
head->next=p;
}
fclose(file);
return head->next;
}
struct node *sort(struct node *head) {
if(head==NULL||head->next==NULL)
return head;
struct node *dummyhead=(struct node *)malloc(sizeof(struct node));
dummyhead->next=head;
struct node* p=head->next,*pre=dummyhead;
while(p!=NULL) {
struct node *temp=p->next;
while(pre->next!=NULL&&pre->next->expscore>p->expscore)
pre=pre->next;
p->next=pre->next;
pre->next=p;
p=temp;
pre=dummyhead;
}
return dummyhead->next;
}