【820复试】编程题/填空题(三)

文章目录

1.输出300~400之间的全部素数,并按每行5个数输出
#include <iostream>
using namespace std;
bool isPrime(int x){
	for(int i=2; i*i<=x; i++)
		if(x%i==0) return false;
	return true;
}
int main(){
	int cnt = 0; //每5个一行
	for(int i=300; i<=400; i++){
		if(isPrime(i)){
			cnt++;
			cout <<i<<' ';
		}
		if(cnt && cnt%5==0){
			cnt=0;
			cout<<endl;
		}
	} 
	return 0;
}

【注意】:注意输出格式,每5行,记录cnt,换行条件为if(cnt && cnt%5==0)

2.求Fibonacci数量的前20个数,并将其分5行输出
#include <iostream>
using namespace std;
int main(){
	int f[21];
	f[1]=1,f[2]=1;
	for(int i=3; i<21; i++){
		f[i]=f[i-1]+f[i-2];
	}
	int cnt = 0;
	for(int i=1; i<21; i++){
		cnt++;
		cout << f[i]<<' ';
		if(cnt && cnt%5==0){
			cnt = 0;
			cout <<endl;
		}
	}
	return 0;
}

斐波那契数列:1,1,2,3,5,8,13。 f[1]=f[2]=1。从第三项开始,每一项都是前两项之和。

3.求数学代数式:

Σ n = 1 10 ( n ! + 3 ) \Sigma_{n=1}^{10}(n!+3) Σn=110(n!+3)

#include <iostream>
using namespace std;
typedef long long LL;
LL func(LL x){
	LL ans = 1;
	while(x){
		ans *= x;
		x--;
	}	
	return ans;
}
int main(){
	int n;
	cin >> n;
	LL ans = 0;
	for(int i=1; i<=n; i++){
		ans += func(i)+3;
	}
	cout << ans;
	return 0;
}
4.输入不多于6位的正整数,要求:①求出它是几位数;②分别输出每一位数字;③按逆序输出各位数字
#include <iostream>
using namespace std;

string f1(int n){
	string ans[]={"","一","两","三","四","五","六"};
	int cnt = 0;
	while(n){
		cnt++;
		n = n/10;
	}
	return ans[cnt];
}
void f2(int n){
	int a[7],i=0;
	while(n){
		a[i]=n%10;
		i++;
		n=n/10;
	}
	for(int j=i-1; j>=0; j--) cout <<a[j];
	cout << endl;
	for(int j=0; j<i; j++)
		cout <<a[j];
	cout << endl;
}
int main(){
	int n;
	cin >> n;
	cout<<"是一个"<<f1(n)<<"位数"<<endl;
	f2(n);
	return 0;
}
5.输入一个数a(0<=a<=9),求a+aa+aaa+…+aaa…aaa的值
int main(){
	int n;
	cin >> n;
	int ans=0;
	int x =n;
	for(int i=1; i<=n; i++){
		ans += x;
		x = x*10+n; //注意这里应该是+n 而不是+x
	}
	cout << ans;
	return 0;
}
6.输入10个整型数字,用冒泡法、(指针)冒泡法、快速排序法、归并排序法、选择排序对这10个数排序,并输出
#include <iostream>
#include<bits/stdc++.h>
using namespace std;

void print(int a[], int n){
	for(int i=0; i<n; i++) cout << a[i]<<' ';
	cout<<endl<<endl;
}

void bubble_sort(int a[],int n){
	for(int i=0; i<n-1; i++){
		for(int j=i+1; j<n; j++){
			if(a[i]>a[j]){
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
	}
	cout<<"bubble_sort:"<<endl;
	print(a,n);
}

void bubble_point_sort(int *a, int n){
	//感觉不是这种指针来做 
	for(int i=0; i<n-1; i++){
		for(int j=i+1; j<n; j++){
			if(*(a+i) > *(a+j)){
				int t = *(a+i);
				*(a+i) = *(a+j);
				*(a+j) = t;
			}
		}
	}
	cout << "bubble_point_sort:"<<endl;
	print(a,n);
}

void quick_sort(int a[],int m, int n){
	if(m>=n) return;
	int l = m, r= n-1;
	int x = a[l+r >> 1];//枢纽 
	while(l<r){
		while(l<r && a[l]<x) l++;
		while(l<r && a[r]>x) r--;
		int t=a[l];
		a[l]=a[r];
		a[r] = t;
	}
	quick_sort(a,m,l);
	quick_sort(a,l+1,n);
} 
void merge(int a[], int left, int mid, int right, int b[]){
    int i = left,j = mid + 1,t = 0;

    while (i <= mid && j <= right)
        if (a[i] <= a[j]) 
            b[t++] = a[i++];
        else
            b[t++] = a[j++];
    
    while (i <= mid)  b[t++] = a[i++];
    while (j <= right) b[t++] = a[j++];

    t = 0;
    int x = left;
    while (x <= right) 
        a[x++] = b[t++];
}


void merge_sort(int a[], int left, int right, int b[]){
	if(left < right){
		int mid = left + right >> 1;
		merge_sort(a,left, mid, b);
		merge_sort(a,mid+1, right, b);
		merge(a,left, mid, right, b);
	}
}

void select_sort(int a[], int n){
	for(int i=0; i<n-1; i++){
		int min = i;
		for(int j=i+1; j<n; j++){
			if(a[j]<a[min]) min = j;
		}
		if(min!=i) swap(a[i],a[min]);
	}
	cout << "select_sort:";
	print(a,n);
}


int main(){
	int a[10];
	for(int i=0; i<10; i++) cin >> a[i];
	
//	bubble_sort(a,10);

//	bubble_point_sort(a,10);

//	quick_sort(a,0,10);
//	cout<<"quick_sort:"<<endl;
//	print(a,10);

//	int b[10];
//	memset(b,0,sizeof(b));
//	merge_sort(a,0,9,b);

//	cout<<"merge_sort:"<<endl;
//	print(a,10);

	select_sort(a,10);
	return 0;
}
7.将一个n*m唯数组a的行和列的元素互换(即行列互换),存到另一个m*n数组b中
#include <iostream>
using namespace std;

void change(int a[][100],int n, int m){
	int b[100][100];
	for(int i=0; i<n; i++){
		for(int j=0; j<m; j++){
			b[j][i] = a[i][j];
		}
	}
	for(int i=0; i<m; i++){
		for(int j=0; j<n; j++){
			cout << b[i][j]<<' ';
		}
		cout << endl;
	}
}

int main(){
	int n, m;
	cin >> n>>m;
	int a[100][100];
	for(int i=0; i<n; i++)
		for(int j=0; j<m; j++)
			cin>>a[i][j];
	change(a,n,m);	
	return 0;
}

二维数组不能开太大,一般数量级开到500*500就已经很大了。

8.输入一行字符,统计其中有多少个单词,单词之间用空格分隔开
#include <iostream>
using namespace std;

int main(){
	char s[1024];
	gets(s);
	int t=0;
	char ans[2048];
	int cnt=0,num=0;
	for(int i=0; s[i]!='\0'; i++){
		if(s[i]>='a'&& s[i]<='z' || s[i]>='A' && s[i]<='Z'){
			ans[cnt++] = s[i];
			t++;
			continue;
		}
		if(t){
			num++;
			ans[cnt++] = ' ';
			t=0;
		}
	}
	ans[cnt]='\0';
	for(int i=0; ans[i]!='\0'; i++) cout << ans[i];
	return 0;
}
9.输入三个字符串,要求找出其中最大者
#include <iostream>
#include<cstring>
using namespace std;

int main(){
	char str1[1024],str2[1024],str3[1024];
	gets(str1);
	gets(str2);
	gets(str3);
	char ans[1024];
	strcpy(ans,str1);
	if(strcmp(ans,str2)) strcpy(ans,str2);
	if(strcmp(ans,str3)) strcpy(ans,str3);
	cout << ans;
	return 0;
}
10.用递归法将一个整数n转换成字符串,如输入483,输出字符串"483",n的位数不确定,可以是任意位数的整数
//常规法
void change_to_string(int n,char *ans){
	int cnt = 0;
	int x = n;
	while(x){
		cnt++;
		x=x/10;
	}
	ans[cnt]='\0';
	for(int i=cnt-1; i>=0; i--){
		ans[i] =n%10+'0';
		n=n/10;
	}
}
//递归法
void function(int n){
	int i,j;
	i=n%10;
	j=n/10;
	if(j>0) function(j);
	printf("%c",i+'0');
}
int main(){
	int n;
	cin >> n;
//	char ans[16];
//	change_to_string(n,ans);
//	puts(ans);
	function(n);
	return 0;
}
11.用指针实现数据b[10]中的元素按逆序存放
void func(int *a, int n){
	int *p=a, *q=a;
	for(int i=0,j=n-1; i<j; i++,j--){
		int t = *(p+i);
		*(p+i)=*(q+j);
		*(q+j) = t;
	}
}

int main(){
	int a[10];
	for(int i=0; i<10; i++) cin >> a[i];
	func(a,10);
	for(int i=0; i<10; i++) cout << a[i]<<' ';
	return 0;
}
12.计算当天是本年中的第几天
int calculate(int year, int month, int day){
	int ans=0;
	int day_tab[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
	for(int i=0; i<month; i++){
		ans += day_tab[i];
	} 
	ans += day;
    //注意是否是闰年
	if(month>=3&&(year % 4 ==0 && year %100!=0 || year % 400==0)) ans++;
	return ans; 
}
int main(){
	int y,m,d;
	scanf("%d-%d-%d",&y,&m,&d);
	cout << calculate(y,m,d);
	return 0;
}
13.设计候选人得票统计程序,要求有4个候选人(分别是Zhang、Wang、Li、Zhao),选民每次输入一个被选人姓名,最后统计出各人的得票结果
#include <iostream>
#include<cstring>
using namespace std;
struct people{
	char name[50];
	int score;
};
int main(){
	struct people s[4]={{"Zhang",0},{"Wang",0},{"Li",0},{"Zhao",0}};
	char xx[50];
	do{
		gets(xx);
		for(int i=0; i<4; i++){
			if(strcmp(xx,s[i].name)==0){
				s[i].score+=1;
			}
		}
	}while(xx[0]!='#');
	for(int i=0; i<4; i++){
		printf("%s得票数为:%d\n",s[i].name,s[i].score);
	}
	return 0;
}


【注意】:
strcmp(str1,str2)的返回值
字符串相等,返回值为1
str1>str2,返回值>0
str1<str2,返回值<0

14.建立动态数组,输入5个学生的成绩,另外用一个函数检查其中有无低于60分的,输出不合格的成绩。
#include <stdio.h>
#include <stdlib.h>

struct Student {
    char name[50];
    double score;
};

void checkLowScores(struct Student *students, int size) {
    printf("成绩低于60分的有:\n");
    for (int i = 0; i < size; i++) {
        if (students[i].score < 60) {
            printf("%s %.2f\n", students[i].name, students[i].score);
        }
    }
}

int main() {
    const int numStudents = 5;
    struct Student *students = (struct Student *)malloc(numStudents * sizeof(struct Student));
    if (students == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 1;
    }

    printf("请输入学生姓名和成绩:\n");
    for (int i = 0; i < numStudents; i++) {
        printf("学生%d:", i + 1);
        if (scanf("%49s %lf", students[i].name, &students[i].score) != 2) {
            fprintf(stderr, "无效输入\n");
            free(students);
            return 1;
        }
    }

    checkLowScores(students, numStudents);
    free(students);
    return 0;
}

15.找出一个n*n维数组中的鞍点,即该位置上的元素在该行上最大、在该列上最小
#include <stdio.h>

void findSaddlePoint(int matrix[][100], int n) {
    // 遍历矩阵的每一行
    for (int i = 0; i < n; i++) {
        // 找到该行的最大值及其列索引
        int maxVal = matrix[i][0];
        int maxCol = 0;
        for (int j = 1; j < n; j++) {
            if (matrix[i][j] > maxVal) {
                maxVal = matrix[i][j];
                maxCol = j;
            }
        }
        // 检查该列上的最小值是否与最大值相等
        int isSaddlePoint = 1;
        for (int k = 0; k < n; k++) {
            if (matrix[k][maxCol] < maxVal) {
                isSaddlePoint = 0;
                break;
            }
        }
        // 如果是鞍点,则输出
        if (isSaddlePoint) {
            printf("鞍点位置:行 %d,列 %d,值为 %d\n", i + 1, maxCol + 1, maxVal);
        }
    }
}
int main() {
    int n;
    printf("请输入矩阵的维数:");
    scanf("%d", &n);

    int matrix[100][100];

    // 输入矩阵元素
    printf("请输入矩阵的元素:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    // 查找鞍点
    findSaddlePoint(matrix, n);

    return 0;
}

16.用一个函数实现将一行字符串中最长的单词输出。

样例输入hello uestcya
样例输出uestcya

#include <stdio.h>
#include <string.h>
#include <ctype.h>

// 函数定义
void findLongestWord(const char *str) {
    //用一个字符数组来记录答案
    char longestWord[100];
    int maxLength = 0; //最大长度
    int currentLength = 0; //当前长度
    const char *currentWordStart = NULL; //当前字符起始位置

    for (int i = 0; str[i] != '\0'; i++) {
        // 判断当前字符是否为字母
        if (isalpha(str[i])) {
            // 如果当前字符是字母且currentWordStart为空,则标记单词开始位置
            if (currentWordStart == NULL) {
                currentWordStart = &str[i];
            }
            currentLength++;
        } else {
            // 如果遇到非字母字符,判断当前单词长度是否大于最大长度,如果是则更新最长单词信息
            if (currentLength > maxLength) {
                maxLength = currentLength;
                strncpy(longestWord, currentWordStart, currentLength);
                longestWord[currentLength] = '\0';
            }
            // 重置当前单词长度和起始位置
            currentLength = 0;
            currentWordStart = NULL;
        }
    }

    // 最后一个单词的处理
    if (currentLength > maxLength) {
        maxLength = currentLength;
        strncpy(longestWord, currentWordStart, currentLength);
        longestWord[currentLength] = '\0';
    }

    // 输出最长单词
    printf("最长的单词是:%s\n", longestWord);
}

int main() {
    char input[100]; // 假设输入的字符串不超过100个字符

    printf("请输入一行字符串:\n");
    fgets(input, sizeof(input), stdin); // 使用fgets()函数读取一行字符串

    // 去除换行符
    input[strcspn(input, "\n")] = '\0';

    // 调用函数查找并输出最长单词
    findLongestWord(input);

    return 0;
}

17.输出金字塔图案
#include <stdio.h>
int main() {
	int n;
	scanf("%d",&n);
	int space_num=n-1;
	for(int i=1; i<=n; i++){
		for(int j=1; j<=space_num; j++) putchar(' ');
		int cnt_star = 1+2*(i-1);
		for(int j=1; j<=cnt_star; j++) putchar('*');
		putchar('\n');
		space_num-=1;
	}
	space_num=1;
	for(int i=n-1; i>=1; i--){
		for(int j=1; j<=space_num; j++) putchar(' ');
		int cnt_star = 1+2*(i-1);
		for(int j=1; j<=cnt_star; j++) putchar('*');
		putchar('\n');
		space_num+=1;
	}
    return 0;
}
/*
输入:5
输出:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
*/
18.电文解密

A–>Z, a–>z, B–>Y, b–>y。即第1个字母变成第26个字母,第i个字母变成第(26-i+1)个字母。非字母符号不变。要求编程序将密码译回原文,并输出密码和原文。

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void decrypt(char *text) {
    int length = strlen(text);
    for (int i = 0; i < length; i++) {
        if (isalpha(text[i])) { // 如果是字母
            char base = isupper(text[i]) ? 'A' : 'a';
            text[i] = base + 25 - (text[i] - base);
        }
    }
}

int main() {
    char password[100];

    printf("输入密码: ");
    scanf("%s", password);

    decrypt(password);

    printf("密码解密后的原文为: %s\n", password);

    return 0;
}
19.写一个函数,将一个字符串中的元音字母复制到另一个字符串,然后输出。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void copyVowels(const char *input, char *output) {
    int i, j = 0;
    // 遍历输入字符串
    for (i = 0; input[i] != '\0'; i++) {
        char c = tolower(input[i]); // 转换为小写字母以方便比较
        // 如果是元音字母,则复制到输出字符串中
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            output[j] = input[i];
            j++;
        }
    }
    output[j] = '\0'; // 添加字符串结束符
}
int main() {
    char input[100], output[100];
    printf("输入一个字符串: ");
    scanf("%s", input);
    copyVowels(input, output);
    printf("元音字母复制后的字符串为: %s\n", output);
    return 0;
}

20.利用两个函数对输入的两个分数进行加、减、乘、除四则运算并输出分数表示的结果。

输入格式%ld/%ld%c%ld/%ld
输出格式%ld/%ld

#include <stdio.h>

// 定义分数结构体
typedef struct {
    long numerator;   // 分子
    long denominator; // 分母
} Fraction;

// 辗转相除法求最大公约数
long gcd(long a, long b) {
    while (b != 0) {
        long temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
// 简化分数
void simplifyFraction(Fraction *frac) {
    long commonFactor = gcd(frac->numerator, frac->denominator);
    frac->numerator /= commonFactor;
    frac->denominator /= commonFactor;
}
// 加法
Fraction add(Fraction frac1, Fraction frac2) {
    Fraction result;
    result.numerator = frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator;
    result.denominator = frac1.denominator * frac2.denominator;
    simplifyFraction(&result);
    return result;
}
// 减法
Fraction subtract(Fraction frac1, Fraction frac2) {
    Fraction result;
    result.numerator = frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator;
    result.denominator = frac1.denominator * frac2.denominator;
    simplifyFraction(&result);
    return result;
}
// 乘法
Fraction multiply(Fraction frac1, Fraction frac2) {
    Fraction result;
    result.numerator = frac1.numerator * frac2.numerator;
    result.denominator = frac1.denominator * frac2.denominator;
    simplifyFraction(&result);
    return result;
}
// 除法
Fraction divide(Fraction frac1, Fraction frac2) {
    Fraction result;
    result.numerator = frac1.numerator * frac2.denominator;
    result.denominator = frac1.denominator * frac2.numerator;
    simplifyFraction(&result);
    return result;
}
int main() {
    Fraction frac1, frac2;
    char operation;
    // 输入两个分数和运算符
    scanf("%ld/%ld%c%ld/%ld", &frac1.numerator, &frac1.denominator, &operation, &frac2.numerator, &frac2.denominator);
    Fraction result;
    // 根据运算符进行相应的运算
    switch (operation) {
        case '+':
            result = add(frac1, frac2);
            break;
        case '-':
            result = subtract(frac1, frac2);
            break;
        case '*':
            result = multiply(frac1, frac2);
            break;
        case '/':
            result = divide(frac1, frac2);
            break;
        default:
            printf("Invalid operation\n");
            return 1;
    }

    // 输出结果
    printf("%ld/%ld\n", result.numerator, result.denominator);

    return 0;
}

21.链表逆序
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};
// 头插法构建链表
struct Node* insertNode(struct Node* head, int value) {
    // 创建新节点
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    // 设置新节点数据
    newNode->data = value;
    // 新节点指向原头节点
    newNode->next = head;
    // 更新头节点为新节点
    head = newNode;
    return head;
}

// 输出链表
void printList(struct Node* head) {
    struct Node* current = head;
    printf("链表输出为: ");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    int n, value;
    struct Node* head = NULL;
    printf("输入链表节点个数: ");
    scanf("%d", &n);
    printf("输入链表数据: \n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        head = insertNode(head, value); // 头插法插入节点
    }
    printList(head); // 输出链表
    // 释放链表内存
    struct Node* temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
    return 0;
}
22.将输入的字符串逆序输出

太简单了,不写了

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    // 输入字符串
    printf("输入字符串: ");
    scanf("%s", str);
    // 获取字符串长度
    int length = strlen(str);
    // 逆序输出字符串
    printf("逆序输出字符串: ");
    for (int i = length - 1; i >= 0; i--) 
        printf("%c", str[i]);
    printf("\n");
    return 0;
}
23.把file1.txt的内容全部复制到file2.txt中,file1.txt中全部是字符(含空格)。要求复制时,在file2.txt中每一行都要加上行号。

例如:行号*(其中"*"表示具体的数字)。最后该函数返回file1.txt中的字符个数(不包含空格)

#include <stdio.h>

int copyFileWithLineNumbers(const char *sourceFilename, const char *destinationFilename) {
    FILE *sourceFile, *destinationFile;
    char ch;
    int characterCount = 0, lineCount = 1;
    // 打开源文件和目标文件
    sourceFile = fopen(sourceFilename, "r");//读源文本文件
    if (sourceFile == NULL) {
        printf("无法打开源文件\n");
        return -1;
    }
    destinationFile = fopen(destinationFilename, "w"); //写文本文件
    if (destinationFile == NULL) {
        printf("无法创建或打开目标文件\n");
        fclose(sourceFile);
        return -1;
    }

    // 逐字符复制并添加行号
    fprintf(destinationFile, "1.");
    while ((ch = fgetc(sourceFile)) != EOF) {
        if (ch != ' ') {
            fputc(ch, destinationFile); //把每个字符依次写入目的文本文件中
            characterCount++; //字符数计数
        }
        if (ch == '\n') {
            lineCount++; //行数
            fprintf(destinationFile, "\n%d.", lineCount); //按格式输出
        }
    }

    // 关闭文件
    fclose(sourceFile);
    fclose(destinationFile);

    return characterCount;
}
int main() {
    int characterCount;
    characterCount = copyFileWithLineNumbers("file1.txt", "file2.txt");
    if (characterCount != -1) {
        printf("file1.txt中的字符个数(不包含空格): %d\n", characterCount);
    }
    return 0;
}

注意:本例中主要是掌握fopen的写法,后面一定要跟一个if判断语句,看文件是否打开成功。
fprintf()的格式:file+内容
fgetc()的格式:file,返回值为字符,每次读一个字符,结束标志位EOF(end of file)
最后记得fclose()。

24.一段名为file.c的程序,该程序中含有括号,现要检查程序中的括号是否配对,提示:利用堆栈实现
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 定义栈结构
struct Stack {
    char data[MAX_SIZE];
    int top;
};
// 初始化栈
void initStack(struct Stack *stack) {
    stack->top = -1;
}
// 判断栈是否为空
int isEmpty(struct Stack *stack) {
    return stack->top == -1;
}
// 入栈操作
void push(struct Stack *stack, char value) {
    if (stack->top == MAX_SIZE - 1) {
        printf("栈已满,无法入栈\n");
        exit(1);
    }
    stack->data[++stack->top] = value;
}
// 出栈操作
char pop(struct Stack *stack) {
    if (isEmpty(stack)) {
        printf("栈为空,无法出栈\n");
        exit(1);
    }
    return stack->data[stack->top--];
}
// 检查括号是否配对
int checkParentheses(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        exit(1);
    }
    struct Stack stack;
    initStack(&stack);
    char ch;
    // 逐字符读取文件内容
    while ((ch = fgetc(file)) != EOF) {
        if (ch == '(' || ch == '[' || ch == '{') {
            // 左括号入栈
            push(&stack, ch);
        } else if (ch == ')' || ch == ']' || ch == '}') {
            // 右括号匹配左括号
            if (isEmpty(&stack)) {
                printf("右括号多余\n");
                fclose(file);
                return 0;
            }
            char top = pop(&stack);
            if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
                printf("括号不匹配\n");
                fclose(file);
                return 0;
            }
        }
    }
    // 检查是否还有未匹配的左括号
    if (!isEmpty(&stack)) {
        printf("左括号多余\n");
        fclose(file);
        return 0;
    }

    fclose(file);
    return 1;
}
int main() {
    const char *filename = "file.c";
    int result = checkParentheses(filename);
    if (result) {
        printf("括号配对正确\n");
    } else {
        printf("括号配对不正确\n");
    }
    return 0;
}
25.将输入的一个数质因分解,如Input:90,Print:90=2*3*3*5
#include <stdio.h>
#include <stdlib.h>
void primeFact(int n){
	for(int i=2; i<=n; i++){
		while(n%i==0){
			printf("%d",i);
			n/=i;
			if(n!=1) putchar('*');
		}
	}
	putchar('\n');
}
int main() {
	int n;
	scanf("%d",&n);
	printf("%d=",n);
	primeFact(n);
    return 0;
}
26.编程求复杂的数学表达式

s u m = 1 − x + x 2 2 ! − x 3 3 ! . . . + x n n ! sum = 1-x +\frac{x^2}{2!}-\frac{x^3}{3!}...+\frac{x^n}{n!} sum=1x+2!x23!x3...+n!xn

#include <stdio.h>
#include <math.h>

double sq(double x, int i){
	double ans = 1;
	for(int j=0; j<i; j++){
		ans *=x;
	}
	return ans;
}
double fib(int x){
	if(x==0) return 1.0;
	double ans = 1.0;
	for(int i=1; i<=x; i++) ans *= i;
	return ans;
}
int main() {
    double ans=0,x;
    int n;
    scanf("%lf %d",&x,&n);
	for(int i=0;i<=n; i++){
		double t = sq(x,i)/fib(i);
		if(i%2==0){
			ans += t;
		}else ans -= t;
	}
	printf("%.5lf",ans);
    return 0;
}
27.一个链表,找出其中数据项最大的结点,然后将其移动到链表尾部,不允许申请新的结点.
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};

// 创建节点
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// 添加节点到链表尾部
void appendNode(struct Node** head, int value) {
    struct Node* newNode = createNode(value);
    if (*head == NULL) {
        *head = newNode;
    } else {
        struct Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

// 查找链表中最大值节点,并移动到链表尾部
void moveMaxNodeToTail(struct Node** head) {
    if (*head == NULL || (*head)->next == NULL) {
        return;
    }
    struct Node* maxPrevious = NULL;
    struct Node* maxNode = *head;
    struct Node* current = *head;
    while (current->next != NULL) {
        //当前结点和已知最大结点比较
        if (current->next->data > maxNode->data) {
            maxPrevious = current; //更新最大结点的前趋结点maxPre
            maxNode = current->next; //更新最大结点maxNode
        }
        current = current->next; //移动当前指针
    }
    if (maxPrevious != NULL) { //如果最大结点的前趋结点不是空
        maxPrevious->next = maxNode->next; //取下maxNode并插入到末尾
        current->next = maxNode;
        maxNode->next = NULL;
    }else{ //即头结点为最大 头指针下移,修改
        struct Node *p=*head;
        *head = (*head)->next;
        current->next = p;
        p->next = NULL;        
    }
}
// 输出链表
void printList(struct Node* head) {
    struct Node* current = head;
    printf("链表输出为: ");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}
// 释放链表内存
void freeList(struct Node* head) {
    struct Node* current = head;
    struct Node* temp;
    while (current != NULL) {
        temp = current;
        current = current->next;
        free(temp);
    }
}

int main() {
    struct Node* head = NULL;
    int value, n;
    printf("输入链表节点个数: ");
    scanf("%d", &n);
    printf("输入链表数据: \n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        appendNode(&head, value); // 添加节点到链表尾部
    }
    // 输出原始链表
    printf("原始链表: ");
    printList(head);
    // 移动最大值节点到链表尾部
    moveMaxNodeToTail(&head);
    printf("处理后的链表: ");
    printList(head);

    // 释放链表内存
    freeList(head);

    return 0;
}

28.编写一个函数,把整数序列分成两个部分,使得左边部分都不大于右边部分,不需要排序。

思路:以数组中某一个值作为分割中心,遍历数组,若大于该值则放right[]数组中,否则放在left[]数组中。然后分别输出left和right数组即可。

#include <stdio.h>

void splitSequence(int *sequence, int length) {
    int left[length], right[length];
    int leftIndex = 0, rightIndex = 0;

    // 遍历整数序列,根据条件分配到左边或右边部分
    for (int i = 0; i < length; i++) {
        if (sequence[i] <= sequence[length / 2]) {
            left[leftIndex++] = sequence[i];
        } else {
            right[rightIndex++] = sequence[i];
        }
    }

    // 输出左边部分序列
    printf("左边部分序列: ");
    for (int i = 0; i < leftIndex; i++) {
        printf("%d ", left[i]);
    }
    printf("\n");

    // 输出右边部分序列
    printf("右边部分序列: ");
    for (int i = 0; i < rightIndex; i++) {
        printf("%d ", right[i]);
    }
    printf("\n");
}

int main() {
    int sequence[100],n;
    scanf("%d",&n);
    for(int i=0; i<n; i++) scanf("%d",&sequence[i]);
    //求长度的一种方法
    //int length = sizeof(sequence) / sizeof(sequence[0]);
    splitSequence(sequence, n);
    return 0;
}

29.有两个整数数组A和B,它们分别由m、n个整数。并且都是按非递减序列,现将B数组插入A数组中,使得A数组中各元素不大于B数组中各元素,且还是非递减序列。

思路:把数组B中小于数组A中最大数据元素的数据插入到A中即可。
初始化两个指针 ij 分别指向数组 A 和数组 B 的起始位置。
遍历数组 A,将指针 i 移动到第一个大于等于当前 B[j] 的位置。
将数组 B 中从 j 开始的元素插入到数组 A 的相应位置。
更新 ij,分别指向插入元素后的下一个位置。
重复步骤 2~4,直到数组 B 中的所有元素都插入到了数组 A 中。

#include <stdio.h>

void mergeArrays(int A[], int m, int B[], int n) {
    int i = m - 1;
    int j = n - 1;
    int k = m + n - 1;//合并后的最大下标

    // 从后向前遍历,将 B 中元素插入到 A 中
    while (i >= 0 && j >= 0) {
        if (A[i] > B[j]) {
            A[k--] = A[i--]; //A最后一个大
        } else {
            A[k--] = B[j--]; //B大
        }
    }
    // 将 B 中剩余元素插入到 A 中
    while (j >= 0) {
        A[k--] = B[j--];
    }
}
int main() {
    int A[] = {1, 3, 0, 0, 0, 0};
    int m = 2;
    int B[] = {2, 4, 6};
    int n = 3;
    mergeArrays(A, m, B, n);
    // 输出合并后的数组 A
    printf("合并后的数组 A:");
    for (int i = 0; i < m + n; i++) {
        printf(" %d", A[i]);
    }
    printf("\n");
    return 0;
}
30.输入两个递增有序整数数列链表La和Lb,将他们合并后,变成一个新的链表,要求该链表递减排序。
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;
    struct Node* next;
};
// 创建新节点
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}
// 添加节点到链表尾部
void appendNode(struct Node** head, int value) {
    struct Node* newNode = createNode(value);
    if (*head == NULL) {
        *head = newNode;
    } else {
        struct Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}
// 合并两个递增有序整数数列链表,并使得合并后的链表递减排序
struct Node* mergeLists(struct Node* La, struct Node* Lb) {
    if (La == NULL)
        return Lb;
    if (Lb == NULL)
        return La;

    // 选择当前节点较大的链表头节点
    if (La->data > Lb->data) {
        struct Node* temp = La;
        La = Lb;
        Lb = temp;
    }

    // 递归合并链表,并递减排序
    La->next = mergeLists(La->next, Lb);
    return La;
}
// 输出链表
void printList(struct Node* head) {
    struct Node* current = head;
    printf("合并后的链表: ");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}
// 释放链表内存
void freeList(struct Node* head) {
    struct Node* current = head;
    struct Node* temp;
    while (current != NULL) {
        temp = current;
        current = current->next;
        free(temp);
    }
}
int main() {
    struct Node* La = NULL; // 第一个链表
    struct Node* Lb = NULL; // 第二个链表
    int value;
    int m, n;
    // 输入第一个链表
    printf("输入第一个链表的长度: ");
    scanf("%d", &m);
    printf("输入第一个链表的元素: ");
    for (int i = 0; i < m; i++) {
        scanf("%d", &value);
        appendNode(&La, value);
    }
    // 输入第二个链表
    printf("输入第二个链表的长度: ");
    scanf("%d", &n);
    printf("输入第二个链表的元素: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        appendNode(&Lb, value);
    }
    // 合并链表并递减排序
    struct Node* result = mergeLists(La, Lb);
    // 输出合并后的链表
    printList(result);
    // 释放链表内存
    freeList(result);
    return 0;
}
31.利用函数对多个字符串进行字典排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void bubbleSort(char *arr[], int n) {
    for (int i = 0; i < n - 1; i++) 
        for (int j = 0; j < n - i - 1; j++) {
            if (strcmp(arr[j],arr[j+1]) > 0) {
                // 交换两个字符串的位置
                char *temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
}

int main() {
    int count;
    printf("输入字符串个数: ");
    scanf("%d", &count);
    // 分配内存来存储字符串指针数组
    char **strings = (char **)malloc(count * sizeof(char *));
    if (strings == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    // 输入字符串
    printf("输入字符串: \n");
    for (int i = 0; i < count; i++) {
        strings[i] = (char *)malloc(100 * sizeof(char)); // 假设每个字符串长度不超过100
        scanf("%s", strings[i]);
    }
    // 对字符串进行冒泡排序
    bubbleSort(strings, count);
    // 输出排序后的字符串
    printf("字典排序后的字符串: \n");
    for (int i = 0; i < count; i++) {
        printf("%s\n", strings[i]);
    }
    // 释放内存
    for (int i = 0; i < count; i++) {
        free(strings[i]);
    }
    free(strings);
    return 0;
}
32.两个字符数组s和t,求t在s中出现第一次的开始位置,如果没有则输出"No",有则输出开始位置(不用strstr)
//暴力匹配法
#include <stdio.h>
#include <string.h>
int findFirstAppearance(char s[], char t[]) {
    int s_len = strlen(s);
    int t_len = strlen(t);
    for (int i = 0; i <= s_len - t_len; i++) {
        int j;
        for (j = 0; j < t_len; j++) {
            if (s[i + j] != t[j]) {
                break; // 如果不匹配,跳出内层循环
            }
        }
        if (j == t_len) {
            return i; // 找到匹配,返回开始位置
        }
    }

    return -1; // 没有找到匹配
}
int main() {
    char s[1024];
    char t[100]; 
	gets(s);
	getchar();
	gets(t);
    int result = findFirstAppearance(s, t);
    if (result == -1) 
        printf("No\n");
    else 
        printf("第一次出现的开始位置: %d\n", result);
    
    return 0;
}

//KMP法
#include <stdio.h>
#include <string.h>
// 构建部分匹配表
void buildPartialMatchTable(char t[], int m, int next[]) {
    int i = 0, j = -1;
    next[0] = -1;
    while (i < m) {
        if (j == -1 || t[i] == t[j]) {
            i++;
            j++;
            next[i] = j;
        } else {
            j = next[j];
        }
    }
}
// 使用KMP算法在s中查找t第一次出现的开始位置
int findFirstAppearance(char s[], char t[]) {
    int n = strlen(s);
    int m = strlen(t);
    int next[m];
    buildPartialMatchTable(t, m, next);
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (j == -1 || s[i] == t[j]) {
            i++;
            j++;
        } else 
            j = next[j];  
    }
    if (j == m) 
        return i - m;
    else 
        return -1;
}

int main() {
    char s[1024];
    char t[100]; 
	gets(s);
	getchar();
	gets(t);
    int result = findFirstAppearance(s, t);
    if (result == -1) {
        printf("No\n");
    } else {
        printf("第一次出现的开始位置: %d\n", result);
    }
    return 0;
}

33.输入若干整数,以数字0结尾,构造逆序的双向链表
#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* pre;
    struct Node* next;
};
struct Node* create_new(int x){
	struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
	if(newNode ==NULL) exit(1);
	newNode->data = x;
	newNode->pre = NULL;
	newNode->next = NULL;
	return newNode;
}
void insert_Node(struct Node **head,int x){
	struct Node *p = create_new(x);
	if(*head==NULL) *head = p;
	else{
		p->next = *head;
		(*head)->pre = p;
		*head = p;
	}
}
void print(struct Node *head){
	printf("打印链表:\n");
	while(head){
		printf("%d ",head->data);
		head = head->next;
	}
}
int main() {
	struct Node *head=NULL;
	int x;
	while(1){
		scanf("%d",&x);
		if(x==0) break;
		insert_Node(&head,x);
	}
	print(head);
    return 0;
}

  • 26
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值