上机代码整理

139 阅读4分钟

机试题目

1、指定位置反转字符

题目:
    将一个字符串在指定位置pqpq<=String.length)进行反转,并与原来字符串形成新的字符串输出,
例如:
    hjskcl1423sfdd(p=5,q=9),输出:hjsk2411c3sfdd
#include <stdio.h>
#include <string.h>
​
void reverse_string(char *str, int p, int q) {
    int i, j;
    char temp;
    for (i = p-1, j = q-1; i < j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}
​
int main() {
    char str[] = "hjskcl1423sfdd";
    int p = 5, q = 9;
    printf("Original string: %s\n", str);
    reverse_string(str, p, q);
    printf("Reversed string: %s\n", str);
    return 0;
}

2、加密解密

1.编制一个程序,将输入的一行字符以加密的形式输出,然后将其解密,解密的字符序列与输入的正文进行比较,吻合时输出解密的正文,否则输出解密失败。
加密时,将每个字符的ASCII码依次反复加上“4 9 6 2 8 7 3”中的数字,并在32(‘’)~122(‘z’)之间做模运算。解密和加密的顺序相反。例如,对于输入正文“the result of 3 and 2 is not 8”,则运行结果为:
    xqk□zlvyuzqn□6$jtf(9#m!&pw#
    the result of 3 and 2 is not 8
#include <iostream>
#include <string>
​
using namespace std;
​
const int KEY_LEN = 7; // 加密和解密时使用的数字序列的长度
const int KEY[KEY_LEN] = {4, 9, 6, 2, 8, 7, 3}; // 加密和解密时使用的数字序列// 加密函数
string encrypt(string s) {
    string result; // 用于保存加密后的字符串
    for (int i = 0; i < s.length(); i++) { // 遍历输入字符串中的每个字符
        int ascii_code = static_cast<int>(s[i]); // 将字符转换为 ASCII 码
        for (int j = 0; j < KEY_LEN; j++) { // 反复执行数字序列中的加法和模运算操作
            ascii_code += KEY[j];
            ascii_code %= 91; // 对结果进行模运算,确保在32~122之间
            ascii_code += 32;
        }
        result += static_cast<char>(ascii_code); // 将加密后的字符拼接到结果字符串中
    }
    return result; // 返回加密后的字符串
}
​
// 解密函数
string decrypt(string s) {
    string result; // 用于保存解密后的字符串
    for (int i = 0; i < s.length(); i++) { // 遍历输入字符串中的每个字符
        int ascii_code = static_cast<int>(s[i]); // 将字符转换为 ASCII 码
        for (int j = KEY_LEN - 1; j >= 0; j--) { // 反复执行数字序列中的减法和模运算操作
            ascii_code -= KEY[j];
            if (ascii_code < 32) { // 处理解密后的 ASCII 码小于32的情况
                ascii_code += 91;
            }
            ascii_code %= 91;
            ascii_code += 32;
        }
        result += static_cast<char>(ascii_code); // 将解密后的字符拼接到结果字符串中
    }
    return result; // 返回解密后的字符串
}
​
int main() {
    string s;
    getline(cin, s); // 输入一行字符
​
    string encrypted_text = encrypt(s); // 进行加密操作
    cout << "Encrypted text: " << encrypted_text << endl;
​
    string decrypted_text = decrypt(encrypted_text); // 进行解密操作
    if (decrypted_text == s) { // 判断解密后的字符串是否等于输入字符串
        cout << "Decryption succeeded!" << endl;
        cout << "Original text: " << decrypted_text << endl;
    } else {
        cout << "Decryption failed!" << endl;
    }
​
    return 0;
}
​

2、字符和数字分割

#include <stdio.h>
#include <string.h>
#include <ctype.h>void split_string(char *str, char *str_char, char *str_int) {
    int i, j, k;
    j = k = 0;
    for (i = 0; i < strlen(str); i++) {
        if (isalpha(str[i])) {
            str_char[j++] = str[i];
        } else if (isdigit(str[i])) {
            str_int[k++] = str[i];
        }
    }
    str_char[j] = '\0';
    str_int[k] = '\0';
}
​
int main() {
    char str[] = "ks47ks18m9ws4";
    char str_char[strlen(str)], str_int[strlen(str)];
    split_string(str, str_char, str_int);
    printf("Original string: %s\n", str);
    printf("String with only characters: %s\n", str_char);
    printf("String with only integers: %s\n", str_int);
    return 0;
}

3、头插法反转链表

两个链表,一个字符链表,一个数字链表,要求输入和输出相反
​
#include <stdio.h>
#include <stdlib.h>/* 定义链表节点结构体 */
struct Node {
    char data;
    struct Node *next;
};
​
/* 头插法创建链表 */
struct Node* createList(int n) {
    struct Node *head, *p;
    int i;
    char x;
​
    /* 创建头节点 */
    head = (struct Node *) malloc(sizeof(struct Node));
    if (head == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    head->next = NULL;
​
    /* 依次插入新节点 */
    for (i = 0; i < n; i++) {
        printf("Enter the data for node %d: ", i+1);
        scanf(" %c", &x); /* 注意:这里使用了空格来跳过前一个输入的回车符 */
        p = (struct Node *) malloc(sizeof(struct Node));
        if (p == NULL) {
            printf("Memory allocation failed.\n");
            exit(1);
        }
        p->data = x;
        p->next = head->next;
        head->next = p;
    }
​
    return head;
}
/* 打印链表的所有节点 */
void printList(struct Node *head) {
    struct Node *p = head->next;
    while (p != NULL) {
        printf("%c ", p->data);
        p = p->next;
    }
    printf("\n");
}
​
int main() {
    int n;
    struct Node *head;
​
    printf("Enter the number of nodes: ");
    scanf("%d", &n);
​
    head = createList(n);
    printf("The created list is: ");
    printList(head);
    return 0;
}

4、斐波那契数列

输入一个数值n,要求输出前n个斐波那契数,每五个一行
#include <stdio.h>
​
/* 计算斐波那契数列的第n项 */
int fibonacci(int n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else {
        return fibonacci(n-1) + fibonacci(n-2);
    }
}
​
int main() {
    int n, i, count = 0;
​
    printf("Enter the number of Fibonacci numbers to output: ");
    scanf("%d", &n);
​
    for (i = 0; i < n; i++) {
        int fib = fibonacci(i);
        printf("%d ", fib);
        count++;
        if (count == 5) {
            printf("\n");
            count = 0;
        }
    }
​
    /* 如果最后一行不足5个数,需要再输出一个换行符 */
    if (count > 0) {
        printf("\n");
    }
​
    return 0;
}

5、冒泡排序

#include <stdio.h>
​
/* 冒泡排序 */
void bubbleSort(int arr[], int n) {
    int i, j;
    for (i = 0; i < n-1; i++) {
        for (j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                /* 交换相邻的两个数 */
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}
​
int main() {
    int arr[] = {5, 2, 8, 6, 1, 9, 3, 7, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int i;
​
    printf("Before sorting: ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
​
    bubbleSort(arr, n);
​
    printf("After sorting: ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n"); 
​
    return 0;
}

6、类似于简单的成绩录入系统

  (1)一次性录取N名学生的学号,姓名,科目,成绩
​
   (2)计算每个学生的平均成绩
​
   (3)计算所有学生某一科目的平均成绩
​
   (4)计算所有科目的平均成绩

7、枚举法

image-20230329200849259

image-20230329200926947

8、素数判别

int prime(int n) {
    int i;
    if (n < 2) {  /* 小于2的数不是素数 */
        return 0;
    }
    for (i = 2; i * i <= n; i++) {
        //判断到平方根范围就可以,因为如果该数有大于 sqrt(n) 的因数的话,那么它就一定会有小于 sqrt(n) 的因数
        if (n % i == 0) {  /* 能被整除说明不是素数 */
            return 0;
        }
    }
    return 1;
}
​

9、模拟

1、图形模拟

#include <stdio.h>
#include <string.h>
#include <ctype.h>
//梯形打印
int main(){
    int h;
    while(scanf("%d",&h)!=EOF){
    int row = h;//行
    int col = h + 2*(h-1);//列
    for(int i = 0;i< row ;i++){
        for(int j = 0;j<col;j++){
            if(j<col-(h+2*i)){
                 printf(" ");
            }else{
            printf("*");
        }
    }
     printf("\n");
   }
 }
}
​

2、日期问题

某个日期是这一年的第几天
​
#include <stdio.h>
#include <string.h>
#include <stdbool.h>int daytab[2][13] = {
    {
        0,31,28,31,30,31,30,31,31,30,31,30,31
    },{
        0,31,29,31,30,31,30,31,31,30,31,30,31
    }
};
bool IsLeapYear(int year){
    return(year%4==0&&year%100!=0)||(year%400==0);
}
int main(){
     int year,month,day;
     while(scanf("%d%d%d",&year,&month,&day)!=EOF){
        int number = 0;
        int row = IsLeapYear(year);
        for(int i =0;i<month;++i){
            number += daytab[row][i];
        }
        number += day;
        printf("%d",number);
     }
}
​

10、比较字符串,输出它们第一个不同字母的位置,大小写不敏感。

#include<bits/stdc++.h>
​
using namespace std;
​
int main() {
    string s1, s2;
    cin >> s1 >> s2;
​
    int n = min(s1.length(), s2.length());
​
    for (int i = 0; i < n; i++) {
        if (tolower(s1[i]) != tolower(s2[i])) {
            cout << "The first different character is at position " << i + 1 << endl;
            return 0;
        }
    }
​
    if (s1.length() != s2.length()) {
        cout << "The first different character is at position " << n + 1 << endl;
    } else {
        cout << "The two strings are identical." << endl;
    }
​
    return 0;
}
​

11、判断一个数是否为回文数。(数字:1234321)

#include <iostream>
​
using namespace std;
​
bool isPalindrome(int x) {
    /*
    判断一个整数是否为回文数
    */
    if (x < 0) {
        return false;
    }
    int num = x;
    int reverse_num = 0;
    while (num) {
        reverse_num = reverse_num * 10 + num % 10;
        num /= 10;
    }
    return (reverse_num == x);
}
​
int main() {
    int x = 12321;
    if (isPalindrome(x)) {
        cout << x << " is a palindrome number." << endl;
    } else {
        cout << x << " is not a palindrome number." << endl;
    }
    return 0;
}

12、 xxx定律

描述
    对于一个数n,如果是偶数,就把n砍掉一半;如果是奇数,把n变成 3*n+ 1后砍掉一半,直到该数变为1为止。     请计算需要经过几步才能将n变到1,具体可见样例。
输入描述:
    测试包含多个用例,每个用例包含一个整数n。(1<=n<=10000)
输出描述:
    对于每组测试用例请输出一个数,表示需要经过的步数,每组输出占一行。
示例1
输入:
3
1
复制
输出:
5
0
#include <iostream>
using namespace std;
​
int main() {
    int n;
    int count = 0;
    cin>>n;
    while (n!=1) {
        if (n%2==0) {
            //n为偶数
            n = n/2;
        }else {
            //n为奇数
            n = 3*n +1;
            n = n/2;
        }
        count++;
    }
    cout<<count;
}
// 64 位输出请用 printf("%lld")

12、输入一个整数n,输出n的阶乘(每组测试用例可能包含多组数据,请注意处理)

#include <iostream>
using namespace std;
​
int main() {
   //递推阶乘
   long long fact[25];
   int n;
   cin>>n;
   fact[0] = 1;
   for (int i = 1; i<=n; ++i) {
        fact[i] = i*fact[i-1];
   }
   cout<<fact[n]<<endl;
}

13、特殊乘法

写个算法,对2个小于1000000000的输入,求结果。 特殊乘法举例:123 * 45 = 1*4 +1*5 +2*4 +2*5 +3*4+3*5
#include <iostream>
using namespace std;
int statusSum(int num){
    int sum = 0;
    while (num>0) {
        sum+=num%10;
        num/=10;
    }
    return sum;
}
int main() {
    int  x,y;
    cin>>x>>y;
    cout<<statusSum(x) * statusSum(y)<<endl;
}
// 64 位输出请用 printf("%lld")

14、最大公约数

#include <iostream>
#include <numeric>
using namespace std;
​
//辗转相除法,两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。
int gcd(int a, int b) {
    //如果b被a整除,那么a是最大公约数,否则,a%b
    return b == 0 ? a : gcd(b, a % b);
}
int main() {
    int a, b;
    cin >> a >> b;
    cout << gcd(a, b);
    return 0;
}
// 64 位输出请用 printf("%lld")

15、守形数

//平方之后低位与之相同  输入包括1个整数N,2<=N<100。
#include <cstdio>
#include <iostream>
using namespace std;
//守形数
int main() {
    int n ;
    while (scanf("%d", &n) != EOF) {
        int sq = n * n;
        if (n < 10) {
            sq %= 10;
            if (sq == n) {
                cout << "Yes!\n";
            } else {
                cout << "No!\n";
            }
        } else if (n < 100) {
            sq %= 100;
            if (sq == n) {
                cout << "Yes!\n";
            } else {
                cout << "No!\n";
            }
        }
    }
    return 0;
}

15、输入字符串,拆分成数字和字母,存入两个链表中

#include <bits/stdc++.h>
​
using namespace std;
​
struct Node {
    char value;
    Node *next;
};
Node* alpha_head = NULL;
Node* num_head = NULL;
​
void insertAlpha(char c) {
    Node* newNode = new Node;
    newNode->value = c;
    newNode->next = alpha_head;
    alpha_head = newNode;
}
​
void insertNum(char num) {
    Node* newNode = new Node;
    newNode->value = num;
    newNode->next = num_head;
    num_head = newNode;
}
int main(){
    string str;
    cout<<"请输入字符串:"; 
    cin>>str;
    for(int i = 0;i<str.length();i++){
        if(isalpha(str[i])){
            insertAlpha(str[i]);
        }else if(isdigit(str[i])){
            insertNum(str[i]);
        }
    }
     cout << "Alphabets: ";
    Node* curr = alpha_head;
    while (curr != NULL) {
        cout << (char) curr->value << " ";
        curr = curr->next;
    }
    cout << endl << "Numbers: ";
    curr = num_head;
    while (curr != NULL) {
        cout << curr->value << " ";
        curr = curr->next;
    }
    cout << endl;
    return 0;
} 

16、全排列

//思路:把字符排序再逐一对比,暴力快捷#include <bits/stdc++.h>
using namespace std;
int isFullm(char *str,char *str1){
    int n = sizeof(str)/sizeof(str[0]);
    sort(str,str+n);
    sort(str1,str1+n) ;
    
    for(int i = 0;i<n;i++){
        if (str[i] != str1[i]) {
            return 0;
        }
    }
    return 1;
}
int main(){
    char str[10],str1[10];
    cout<<"请输入第一个列表 :" ;
    cin>>str; 
    cout<<"请输入第二个列表 :" ; 
    cin>>str1;
    if(isFullm(str,str1)){
        cout<<"两个列表是全排列!"; 
    }else{
        cout<<"两个列表不是全排列!"; 
    }; 
} 

17、统计区间数字个数

#include <bits/stdc++.h>
​
using namespace std;
​
void printSignal(int n){
    for(int i =0;i<n;++i){
        cout<<"*";
    }
}
int main(){
    srand(time(NULL));//随机数种子;
    
    int counts[10] = {0};
    for(int i = 0 ;i<500;i++){
        int num = rand()%100;//生成0-99 
        int range = num/10;//确定该随机数所在区间
        counts[range]++;//区间计数器+1; 
    } 
    
    for(int i =0;i<10;i++){
        cout<<i*10<<"-"<<(i+1)*10-1<<":"<<counts[i];
        printSignal(counts[i]);
        cout<<"\n"; 
    } 
}

18、文件流

#include <bits/stdc++.h>
​
using namespace std;
​
int main(){
    ifstream infile("input.txt");
    ofstream outfile("output.txt");
    if (!infile) {
        cerr << "Error: unable to open input file!" << endl; // 如果打开失败,输出错误信息
        return 1;
    }
    if (!outfile) {
        cerr << "Error: unable to open output file!" << endl; // 如果打开失败,输出错误信息
        return 1;
    }
    
    string shape;
    double length, width, radius;
    const double PI = 3.14159;
    while(infile>>shape){
          if (shape == "rectangle") { // 如果是矩形,读入长和宽,并计算面积
            infile >> length >> width;
            double area = length * width;
            outfile << "The area of the rectangle is " << area << endl;
        } else if (shape == "circle") { // 如果是圆形,读入半径,并计算面积
            infile >> radius;
            double area = PI * pow(radius, 2);
            outfile << "The area of the circle is " << area << endl;
        } else { 
            // 如果不是矩形或圆形,则输出错误信息
            outfile << "Error: unrecognized shape "" << shape << """ << endl;
        }
    }
    infile.close(); // 关闭输入文件
    outfile.close(); // 关闭输出文件
​
    return 0;
}

19、面向对象

#include <iostream>
#include <string>
​
using namespace std;
​
class Student {
public:
    // 构造函数
    Student(string name, int age, double score) {
        this->name = name;
        this->age = age;
        this->score = score;
    }
​
    // 成员函数,输出学生信息
    void print() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "Score: " << score << endl;
    }
​
private:
    string name;   // 姓名
    int age;       // 年龄
    double score;  // 成绩
};
​
int main() {
    Student stu1("Tom", 18, 90.5);
    Student stu2("Jerry", 19, 88.0);
​
    stu1.print();
    stu2.print();
​
    return 0;
}
​