1.編寫函數 int delarr(int a[] ,int n),刪除有n個元素的正整型數組a中所有素數,要求:
1)數組a中剩余元素保持原來次序;
2)將處理后的數組輸出;
3)函數值返回剩余元素個數;
4)不能額外定義新數組。
#include <stdio.h>int prime(int n) {if(n==1)return 0;for(int i=2; i<n/2; i++)if(n%i==0)return 0;return 1;
}int delarr(int a[],int n) {for(int i=0; i<n; i++) {if(prime(i)) {for(int j=i; j<n-1; j++)a[j]=a[j+1];i--;n--;}}for(int i=0; i<n; i++)printf("%4d",a[i]);return n;
}
2.編寫函數bool cmpstr(char *s),判定一個給定字符串s是否對稱,對稱字符串也成為回文,是滿足從左到右和從右到左均相同的字符序列(不考慮默認字符串結尾’\0’)
#include <stdio.h>
#include <stdbool.h>bool cmpstr(char *s) {int count=0;while(s[count]!='\0')count++;int low=0,high=num-1;while(low<high) {if(s[low]!=s[high])return false;low++;high--;}return true;
}
3.編寫遞歸函數float comp(float a[],int n),計算給定n個元素的float型數組中所有元素的算術平均值。
#include <stdio.h>float comp(float a[],int n) {if(n==1)return a[0];return (a[n-1]+(n-1)=comp(a,n-1))/n;
}
4.每個學生的信息卡片包括學號、姓名、年齡三項。定義存儲學生信息的單向鏈表的節點類型;編寫函數,由鍵盤依次輸入n個學生的信息,創建一個用于管理學生信息的單向鏈表。
#include <stdio.h>
#include <stdlib.h>typedef struct student {int id;char name[10];int age;struct student *next;
} student;struct student *create(int n) {struct student *head=NULL,*p1,*p2;for(int i=0; i<n; i++) {p1=(struct student *)malloc(sizeof(struct student));scanf("%d%s%d",&(p1->id),&(p1->name),&(p1->age));if(i==0)head=p1;elsep2->next=p1;p2=p1;}p2->next=NULL;return head;
}
5.編寫函數,把上中創建的單向鏈表中所有年齡為z的結點刪除(z的指由用戶鍵盤輸入,且年齡為z的結點可能有多個),將處理后的單向鏈表的所有學生信息存儲到名為output.txt的文本文件中。
#include <stdio.h>
#include <stdlib.h>typedef struct student {int id;char name[10];int age;struct student *next;
} student;void save(struct student *head,int z) {FILE *file;if((file=fopen("output.txt","w"))==NULL) {printf("open error");exit(0);}while(head!=NULL&&head->age==z)head=head->next;struct student *p=head,*q=NULL;while(p!=NULL) {if(p->age!=z)q=p;elseq->next=p->next;p=p->next;}while(head!=NULL) {fprintf(file,"%5d\n%10s%5d\n",head->id,head->name,head->age);head=head->next;}fclose(file);
}