c++面向对象编程题精选收录

c++面向对象程序设计

{% tabs 标签组名称, 默认激活序号 %}
<!-- tab 第一个标签 @图标类名 -->
这里是第一个标签的内容
可以包含Markdown语法、图片、代码等
<!-- endtab -->
<!-- tab 第二个标签 @图标类名 -->
这里是第二个标签的内容
<!-- endtab -->
<!-- tab 第三个标签 -->
这里是第三个标签的内容
<!-- endtab -->
{% endtabs %}

默认警告提示

文章过期提醒

信息提示(现代样式)

pie title 文章分类统计
    "实用教程" : 25
    "博客搭建" : 12
graph TD
    A[开始] --> B[结束]

1.函数

(1)编写一个函数,计算直角坐标系中点 a(x0,y0)到点 b(x1,y1)的距离。

#include <iostream>
#include <cmath>

double calculateDistance(double x0, double y0, double x1, double y1) {
    return sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
}

int main() {
    double x0, y0, x1, y1;
    cin >> x0 >> y0 >> x1 >> y1;
    cout << calculateDistance(x0, y0, x1, y1) << endl;
    return 0;
}

(2)求 a!+b!+c!的值,其中求n!要用一个函数实现,通过主函数输入a,b和c的值,并在主函数中输出计算的结果。

#include <iostream>

long long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    long long result = 1;
    for (int i = 2; i <= n; ++i) {
        result *= i;
    }
    return result;
}

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    cout << factorial(a) + factorial(b) + factorial(c) << endl;
    return 0;
}

(3)编写一个函数。该函数读入一个整数,并判断这个整数是否为一个回文数字。例如4,44,434,4334,43534都是回文数字。

#include <iostream>

bool isPalindrome(int num) {
    int original = num, reversed = 0, remainder;
    while (num != 0) {
        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num /= 10;
    }
    return original == reversed;
}

int main() {
    int num;
    cin >> num;
    if (isPalindrome(num)) {
        cout << num << " 是回文数" << endl;
    } else {
        cout << num << " 不是回文数" << endl;
    }
    return 0;
}

(4)编写一个程序,为选修3,4和5门课程的学生计算平均分,其中求平均分要用重载函数实现。

#include <iostream>

double average(int a, int b, int c) {
    return (a + b + c) / 3.0;
}

double average(double a, double b, double c) {
    return (a + b + c) / 3.0;
}

int main() {
    int choice;
    cin >> choice;
    
    if (choice == 1) {
        int a, b, c;
        cin >> a >> b >> c;
        cout << average(a, b, c) << endl;
    } else if (choice == 2) {
        double a, b, c;
        cin >> a >> b >> c;
        cout << average(a, b, c) << endl;
    }
    return 0;
}

(5)用递归方法将一个整数n转换成字符串。例如,输入512,应输出字符串”512”

#include <iostream>
#include <string>

std::string intToString(int n) {
    if (n == 0) return "0";  
    if (n < 0) return "-" + intToString(-n);  
    if (n < 10) return std::string(1, '0' + n);  
    return intToString(n / 10) + std::string(1, '0' + n % 10);  
}

int main() {
    int n;
    cin >> n;
    cout << intToString(n) << endl;
    return 0;
}

(6)编写一个函数。该函数读入一个整数,然后将这个整数上每个位的数字按照相反的
顺序输出。例如输入的整数为12345,输出结果为54321。

#include <iostream>

void reverseNumber(int n) {
    while (n != 0) {
        cout << n % 10;
        n /= 10;
    }
}

int main() {
    int n;
    cin >> n;
    reverseNumber(n);
    cout << endl;
    return 0;
}

(7)输入3个数字,数字可以为整形或浮点型,分别编写函数来求解3个数字的最大值最小值和平均值,要求在主函数中完成数字的输入和计算结果的输出。

#include <iostream>
#include <algorithm>

template <typename T>
T findMax(T a, T b, T c) {
    return std::max({a, b, c});
}

template <typename T>
T findMin(T a, T b, T c) {
    return std::min({a, b, c});
}

template <typename T>
double findAverage(T a, T b, T c) {
    return (a + b + c) / 3.0;
}

int main() {
    int type;
    cin >> type;

    if (type == 1) {
        int a, b, c;
        cin >> a >> b >> c;
        cout << findMax(a, b, c) << endl;
        cout << findMin(a, b, c) << endl;
        cout << findAverage(a, b, c) << endl;
    } else if (type == 2) {
        double a, b, c;
        cin >> a >> b >> c;
        cout << findMax(a, b, c) << endl;
        cout << findMin(a, b, c) << endl;
        cout << findAverage(a, b, c) << endl;
    }
    return 0;
}

2.构造数据类型

(1)编写函数,完成指定二维数组(3*3)的转置,即行列对换。

#include <iostream>

void transpose(int arr[3][3]) {
    int temp[3][3];
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            temp[j][i] = arr[i][j];
        }
    }
    // 输出转置后的数组
    cout << "转置后的数组: " << endl;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << temp[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    transpose(arr);
    return 0;
}

(2)编写一个程序,要求当输入一个数字月份时,程序输出该月的英文名称。例如输入5 时,程序输出“May”,要求用指针数组实现。

#include <iostream>

void printMonthName(int month) {
    const char* months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    if (month >= 1 && month <= 12) {
        cout << months[month] << endl;
    } else {
        cout << "无效月份" << endl;
    }
}

int main() {
    int month;
    cout << "请输入月份(1-12): ";
    cin >> month;
    printMonthName(month);
    return 0;
}

(3)编写一个程序,要求分别输入5个学生的3科成绩,并输出平均成绩最高的学生的姓名及各科成绩。要求用结构体数组实现。

#include <iostream>
#include <string>

struct Student {
    string name;
    int scores[3];
    double average;
};

void calculateAverage(Student& student) {
    student.average = (student.scores[0] + student.scores[1] + student.scores[2]) / 3.0;
}

int main() {
    Student students[5];
    double maxAverage = 0;
    int maxIndex = 0;

    // 输入5个学生的姓名和成绩
    for (int i = 0; i < 5; ++i) {
        cout << "请输入学生 " << i + 1 << " 的姓名: ";
        cin >> students[i].name;
        cout << "请输入学生 " << i + 1 << " 的三科成绩: ";
        cin >> students[i].scores[0] >> students[i].scores[1] >> students[i].scores[2];
        calculateAverage(students[i]);
        if (students[i].average > maxAverage) {
            maxAverage = students[i].average;
            maxIndex = i;
        }
    }

    // 输出平均成绩最高的学生
    cout << "平均成绩最高的学生是: " << students[maxIndex].name << endl;
    cout << "各科成绩: " << students[maxIndex].scores[0] << " " << students[maxIndex].scores[1] << " " << students[maxIndex].scores[2] << endl;
    return 0;
}

(4)编写一个程序,实现方程式的相加。例如,输入以下两个方程式:

12a+4b-5c=7

2a-8b+3c-6
相加之后有:
14a-4b-2c=13
要求用字符数组实现。

#include <iostream>
#include <cstring>

void addEquations(char* eq1, char* eq2, char* result) {
    int a1, b1, c1, d1;
    int a2, b2, c2, d2;
    sscanf(eq1, "%da+%db+%dc=%d", &a1, &b1, &c1, &d1);
    sscanf(eq2, "%da+%db+%dc=%d", &a2, &b2, &c2, &d2);
    
    int a = a1 + a2;
    int b = b1 + b2;
    int c = c1 + c2;
    int d = d1 + d2;
    
    sprintf(result, "%da+%db+%dc=%d", a, b, c, d);
}

int main() {
    char eq1[] = "12a+4b-5c=7";
    char eq2[] = "2a-8b+3c-6";
    char result[100];
    
    addEquations(eq1, eq2, result);
    
    cout << "相加之后有: " << result << endl;
    return 0;
}

(5)编写一个函数,利用指针将一个字符串反向输出。编写相应的主函数对其进行调用,在主函数中完成原始数据的输入和结果输出。

#include <iostream>

void reverseString(char* str) {
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    
    for (int i = length - 1; i >= 0; --i) {
        cout << str[i];
    }
    cout << endl;
}

int main() {
    char str[100];
    cout << "请输入字符串: ";
    cin >> str;
    reverseString(str);
    return 0;
}

(6)编写一个函数,统计并返回一行文字中所有的字母、数字、空格及其他字符的个数,同时编写相应的主函数,在主函数中能接收用户输入的一行文本,然后调用上面定义的函数,并在主函数中输出各种字符的个数。

#include <iostream>

void countCharacters(const char* text, int& letters, int& digits, int& spaces, int& others) {
    letters = digits = spaces = others = 0;
    while (*text) {
        if (isalpha(*text)) {
            letters++;
        } else if (isdigit(*text)) {
            digits++;
        } else if (isspace(*text)) {
            spaces++;
        } else {
            others++;
        }
        text++;
    }
}

int main() {
    char text[100];
    cout << "请输入一行文本: ";
    cin.getline(text, 100);

    int letters, digits, spaces, others;
    countCharacters(text, letters, digits, spaces, others);
    
    cout << "字母: " << letters << endl;
    cout << "数字: " << digits << endl;
    cout << "空格: " << spaces << endl;
    cout << "其他字符: " << others << endl;
    return 0;
}

3. 面向对象编程

(1)定义一个圆类 Circle,在其中包含1个数据成员表示半径,3个成员函数分别实现半径的输面积的计算和半径、面积的输出,并编写相应的 main 函数测试该类。

#include <iostream>
using namespace std;

class Circle {
private:
    double radius;

public:
    // 构造函数
    Circle(double r) : radius(r) {}

    // 计算面积
    double calculateArea() {
        return 3.14159 * radius * radius;
    }

    // 输出半径和面积
    void printInfo() {
        cout << "半径: " << radius << endl;
        cout << "面积: " << calculateArea() << endl;
    }
};

int main() {
    double r;
    cout << "请输入圆的半径: ";
    cin >> r;

    Circle c(r);
    c.printInfo();

    return 0;
}

(2)以下是一个学生类(Student)的类定义部分。请完成相应的类的实现部分,并编写相应的main 函数测试相应的功能。

#include <iostream.h>
class Student
{ 

 private:
​	int number;
​	char name[20];
​	Date birth;
public:
​	Student;
​	Student(int n,char *m,Date d):
​	Student(const Student &s);
​	~Student();
​	void setnumber(int n);
​	void setname(char *s):
​	void setbirth(Date d);
​	void printstudent();
    
#include <iostream>
#include <cstring>
using namespace std;

struct Date {
    int day, month, year;
};

class Student {
private:
    int number;
    char name[20];
    Date birth;

public:
    // 构造函数
    Student(int n, char* m, Date d) {
        number = n;
        strcpy(name, m);
        birth = d;
    }

    // 拷贝构造函数
    Student(const Student& s) {
        number = s.number;
        strcpy(name, s.name);
        birth = s.birth;
    }

    // 析构函数
    ~Student() {}

    // 设置学号
    void setNumber(int n) {
        number = n;
    }

    // 设置姓名
    void setName(char* s) {
        strcpy(name, s);
    }

    // 设置出生日期
    void setBirth(Date d) {
        birth = d;
    }

    // 输出学生信息
    void printStudent() {
        cout << "学号: " << number << endl;
        cout << "姓名: " << name << endl;
        cout << "出生日期: " << birth.day << "/" << birth.month << "/" << birth.year << endl;
    }
};

int main() {
    Date birthDate = {15, 8, 2000};
    Student s(12345, "张三", birthDate);
    s.printStudent();

    return 0;
}

(3)设计一个点类Point,其中包含点的坐标x和y两个数据成员,并设计两个友元函数分别计算两点间的水平距离和垂直距离。

#include <iostream>
using namespace std;

class Point {
private:
    double x, y;

public:
    // 构造函数
    Point(double xCoord, double yCoord) : x(xCoord), y(yCoord) {}

    // 友元函数声明
    friend double horizontalDistance(const Point& p1, const Point& p2);
    friend double verticalDistance(const Point& p1, const Point& p2);
};

// 计算水平距离
double horizontalDistance(const Point& p1, const Point& p2) {
    return abs(p1.x - p2.x);
}

// 计算垂直距离
double verticalDistance(const Point& p1, const Point& p2) {
    return abs(p1.y - p2.y);
}

int main() {
    Point p1(3, 4), p2(7, 10);

    cout << "水平距离: " << horizontalDistance(p1, p2) << endl;
    cout << "垂直距离: " << verticalDistance(p1, p2) << endl;

    return 0;
}

4.继承和派生

(1)分别定义一个日期类和时间类,然后派生出一个新的日期时间类。请以继承方式实现该类。

#include <iostream>
using namespace std;

// 日期类
class Date {
private:
    int day, month, year;

public:
    Date(int d, int m, int y) : day(d), month(m), year(y) {}

    void printDate() {
        cout << "日期: " << day << "/" << month << "/" << year << endl;
    }
};

// 时间类
class Time {
private:
    int hour, minute, second;

public:
    Time(int h, int m, int s) : hour(h), minute(m), second(s) {}

    void printTime() {
        cout << "时间: " << hour << ":" << minute << ":" << second << endl;
    }
};

// 日期时间类,通过继承 Date 和 Time
class DateTime : public Date, public Time {
public:
    DateTime(int d, int m, int y, int h, int min, int s)
        : Date(d, m, y), Time(h, min, s) {}

    void printDateTime() {
        printDate();
        printTime();
    }
};

int main() {
    DateTime dt(12, 9, 2023, 14, 30, 45);
    dt.printDateTime();

    return 0;
}

(2)在例7-16 的基础上,由 Student 类和 Teacher 类派生出一个描述在职读书的教师的
类,并编写出相应的测试代码。

#include <iostream>
#include <string>
using namespace std;

// 学生类
class Student {
protected:
    string name;
    int age;

public:
    Student(string n, int a) : name(n), age(a) {}

    virtual void printInfo() {
        cout << "姓名: " << name << endl;
        cout << "年龄: " << age << endl;
    }
};

// 教师类
class Teacher : public Student {
protected:
    string subject;

public:
    Teacher(string n, int a, string sub) : Student(n, a), subject(sub) {}

    void printInfo() override {
        Student::printInfo();
        cout << "科目: " << subject << endl;
    }
};

// 在职读书教师类
class InServiceStudentTeacher : public Teacher {
private:
    string studyProgram;

public:
    InServiceStudentTeacher(string n, int a, string sub, string study) 
        : Teacher(n, a, sub), studyProgram(study) {}

    void printInfo() override {
        Teacher::printInfo();
        cout << "学习项目: " << studyProgram << endl;
    }
};

int main() {
    InServiceStudentTeacher teacher("李老师", 35, "数学", "硕士研究生");
    teacher.printInfo();
    return 0;
}

(3)设计一个抽象类,并由它派生出圆柱体、球体和正方体3个类,实现计算圆柱体,球体和正方体表面积和体积;要求按照运行时多态性的方法设计主函数,进行测试。

#include <iostream>
#include <cmath>
using namespace std;

// 抽象类:形状
class Shape {
public:
    virtual double area() = 0;  // 计算表面积
    virtual double volume() = 0; // 计算体积
    virtual ~Shape() {}
};

// 圆柱体类
class Cylinder : public Shape {
private:
    double radius, height;

public:
    Cylinder(double r, double h) : radius(r), height(h) {}

    double area() override {
        return 2 * M_PI * radius * (radius + height);  // 圆柱表面积
    }

    double volume() override {
        return M_PI * radius * radius * height;  // 圆柱体积
    }
};

// 球体类
class Sphere : public Shape {
private:
    double radius;

public:
    Sphere(double r) : radius(r) {}

    double area() override {
        return 4 * M_PI * radius * radius;  // 球体表面积
    }

    double volume() override {
        return (4.0 / 3) * M_PI * radius * radius * radius;  // 球体积
    }
};

// 正方体类
class Cube : public Shape {
private:
    double side;

public:
    Cube(double s) : side(s) {}

    double area() override {
        return 6 * side * side;  // 正方体表面积
    }

    double volume() override {
        return side * side * side;  // 正方体积
    }
};

int main() {
    Shape* shape;

    // 测试圆柱体
    shape = new Cylinder(5, 10);
    cout << "圆柱体表面积: " << shape->area() << endl;
    cout << "圆柱体体积: " << shape->volume() << endl;

    // 测试球体
    shape = new Sphere(5);
    cout << "球体表面积: " << shape->area() << endl;
    cout << "球体体积: " << shape->volume() << endl;

    // 测试正方体
    shape = new Cube(4);
    cout << "正方体表面积: " << shape->area() << endl;
    cout << "正方体体积: " << shape->volume() << endl;

    delete shape;
    return 0;
}

5.运算符重载

(1)在例 8-1的基础上,设计一个表示复数的类 Complex,并在该类中对运算符“+”、“-”、“*”、“/”和“=”进行重载,以实现两个复数的加、减、乘、除以及赋值运算。

#include <iostream>
using namespace std;

class Complex {
private:
    double real, imag; // 实部和虚部

public:
    // 构造函数
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // 运算符重载:加法
    Complex operator+(const Complex& c) {
        return Complex(real + c.real, imag + c.imag);
    }

    // 运算符重载:减法
    Complex operator-(const Complex& c) {
        return Complex(real - c.real, imag - c.imag);
    }

    // 运算符重载:乘法
    Complex operator*(const Complex& c) {
        return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
    }

    // 运算符重载:除法
    Complex operator/(const Complex& c) {
        double denom = c.real * c.real + c.imag * c.imag;
        return Complex((real * c.real + imag * c.imag) / denom, (imag * c.real - real * c.imag) / denom);
    }

    // 运算符重载:赋值
    Complex& operator=(const Complex& c) {
        if (this != &c) { // 防止自赋值
            real = c.real;
            imag = c.imag;
        }
        return *this;
    }

    // 输出复数
    void print() const {
        cout << real << " + " << imag << "i" << endl;
    }
};

int main() {
    Complex c1(4, 5), c2(2, 3), result;

    cout << "c1: ";
    c1.print();
    cout << "c2: ";
    c2.print();

    result = c1 + c2;
    cout << "c1 + c2: ";
    result.print();

    result = c1 - c2;
    cout << "c1 - c2: ";
    result.print();

    result = c1 * c2;
    cout << "c1 * c2: ";
    result.print();

    result = c1 / c2;
    cout << "c1 / c2: ";
    result.print();

    Complex c3;
    c3 = c1; // 测试赋值运算符
    cout << "c3 = c1: ";
    c3.print();

    return 0;
}

(2)设计一个类来实现重载自加运算符的两种形式,即前缀运算符++a 和后缀运算符 a++。

#include <iostream>
using namespace std;

class Counter {
private:
    int value;

public:
    // 构造函数
    Counter(int v = 0) : value(v) {}

    // 前缀自加运算符重载
    Counter& operator++() {
        ++value;
        return *this;
    }

    // 后缀自加运算符重载
    Counter operator++(int) {
        Counter temp = *this;
        ++value;
        return temp;
    }

    // 输出当前值
    void print() const {
        cout << "当前值: " << value << endl;
    }
};

int main() {
    Counter c1(5), c2(10);

    // 前缀自加
    cout << "c1: ";
    c1.print();
    ++c1;  // 前缀自加
    cout << "c1 after ++: ";
    c1.print();

    // 后缀自加
    cout << "c2: ";
    c2.print();
    c2++;  // 后缀自加
    cout << "c2 after c2++: ";
    c2.print();

    return 0;
}

6. 模板

(1)在例9-4的基础上,继续实现单向链表类模板中能够实现节点的插入、删除、排序等的成员函数。

#include <iostream>
using namespace std;

// 单向链表节点类
template <typename T>
class Node {
public:
    T data;         // 数据部分
    Node* next;     // 指向下一个节点的指针

    Node(T val) : data(val), next(nullptr) {}
};

// 单向链表类模板
template <typename T>
class LinkedList {
private:
    Node<T>* head;

public:
    // 构造函数
    LinkedList() : head(nullptr) {}

    // 析构函数
    ~LinkedList() {
        Node<T>* current = head;
        while (current != nullptr) {
            Node<T>* nextNode = current->next;
            delete current;
            current = nextNode;
        }
    }

    // 插入节点
    void insert(T val) {
        Node<T>* newNode = new Node<T>(val);
        newNode->next = head;
        head = newNode;
    }

    // 删除指定节点
    void remove(T val) {
        Node<T>* current = head;
        Node<T>* prev = nullptr;

        // 找到节点
        while (current != nullptr && current->data != val) {
            prev = current;
            current = current->next;
        }

        if (current == nullptr) {
            cout << "元素 " << val << " 不存在!" << endl;
            return;
        }

        // 删除节点
        if (prev == nullptr) {
            head = current->next;  // 删除头节点
        } else {
            prev->next = current->next;
        }
        delete current;
    }

    // 打印链表
    void print() {
        Node<T>* current = head;
        while (current != nullptr) {
            cout << current->data << " ";
            current = current->next;
        }
        cout << endl;
    }

    // 排序链表(使用冒泡排序)
    void sort() {
        if (head == nullptr) return;
        bool swapped;
        do {
            swapped = false;
            Node<T>* current = head;
            while (current != nullptr && current->next != nullptr) {
                if (current->data > current->next->data) {
                    swap(current->data, current->next->data);
                    swapped = true;
                }
                current = current->next;
            }
        } while (swapped);
    }
};

int main() {
    LinkedList<int> list;
    
    list.insert(3);
    list.insert(1);
    list.insert(4);
    list.insert(5);
    list.insert(2);
    
    cout << "原始链表: ";
    list.print();
    
    list.remove(4);  // 删除元素 4
    cout << "删除元素 4 后: ";
    list.print();
    
    list.sort();  // 排序链表
    cout << "排序后的链表: ";
    list.print();

    return 0;
}

(2)设计一个函数模板,实现在一个给定的有序数组中查找给定的元素值是否存在,如果存在则输出该元素在数组中的下标值,如果未找到,则输出-1,并编写相应的程序测试该函数模板。

#include <iostream>
using namespace std;

// 函数模板:在有序数组中查找元素
template <typename T>
int binarySearch(T arr[], int size, T value) {
    int left = 0, right = size - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == value) {
            return mid;  // 找到元素,返回下标
        } else if (arr[mid] < value) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;  // 未找到元素,返回 -1
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int value;

    cout << "请输入要查找的元素: ";
    cin >> value;

    int index = binarySearch(arr, size, value);
    
    if (index != -1) {
        cout << "元素 " << value << " 在数组中的下标是: " << index << endl;
    } else {
        cout << "元素 " << value << " 不存在于数组中!" << endl;
    }

    return 0;
}

7.文件

(1)编写程序,打开指定的一个文本文件,并能在其中每一行的前面加上行号和一个空格符。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void addLineNumbers(const string& inputFile, const string& outputFile) {
    ifstream inFile(inputFile);
    ofstream outFile(outputFile);
    
    if (!inFile) {
        cout << "无法打开输入文件!" << endl;
        return;
    }

    if (!outFile) {
        cout << "无法打开输出文件!" << endl;
        return;
    }

    string line;
    int lineNumber = 1;
    while (getline(inFile, line)) {
        outFile << lineNumber << " " << line << endl;
        lineNumber++;
    }

    inFile.close();
    outFile.close();
}

int main() {
    string inputFile, outputFile;
    cout << "请输入输入文件名: ";
    cin >> inputFile;
    cout << "请输入输出文件名: ";
    cin >> outputFile;

    addLineNumbers(inputFile, outputFile);

    cout << "文件处理完成!" << endl;
    return 0;
}

(2)编写程序,统计一篇英文文章中英文单词的个数以及文章的总行数。

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;

bool isWordCharacter(char c) {
    return isalpha(c) || c == '\'';
}

int countWords(const string& line) {
    int wordCount = 0;
    bool inWord = false;
    for (char c : line) {
        if (isWordCharacter(c)) {
            if (!inWord) {
                inWord = true;
                wordCount++;
            }
        } else {
            inWord = false;
        }
    }
    return wordCount;
}

void countWordsAndLines(const string& filename) {
    ifstream inFile(filename);
    
    if (!inFile) {
        cout << "无法打开文件!" << endl;
        return;
    }

    string line;
    int totalLines = 0;
    int totalWords = 0;
    
    while (getline(inFile, line)) {
        totalLines++;
        totalWords += countWords(line);
    }

    inFile.close();

    cout << "文章的总行数: " << totalLines << endl;
    cout << "文章中的单词总数: " << totalWords << endl;
}

int main() {
    string filename;
    cout << "请输入文章文件名: ";
    cin >> filename;

    countWordsAndLines(filename);

    return 0;
}

(3)编写程序,完成两个文件的连接操作。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void concatenateFiles(const string& file1, const string& file2, const string& outputFile) {
    ifstream inFile1(file1);
    ifstream inFile2(file2);
    ofstream outFile(outputFile);
    
    if (!inFile1 || !inFile2) {
        cout << "无法打开输入文件!" << endl;
        return;
    }

    if (!outFile) {
        cout << "无法打开输出文件!" << endl;
        return;
    }

    string line;
    
    // 先写入第一个文件的内容
    while (getline(inFile1, line)) {
        outFile << line << endl;
    }

    // 然后写入第二个文件的内容
    while (getline(inFile2, line)) {
        outFile << line << endl;
    }

    inFile1.close();
    inFile2.close();
    outFile.close();
}

int main() {
    string file1, file2, outputFile;
    cout << "请输入第一个文件名: ";
    cin >> file1;
    cout << "请输入第二个文件名: ";
    cin >> file2;
    cout << "请输入输出文件名: ";
    cin >> outputFile;

    concatenateFiles(file1, file2, outputFile);

    cout << "文件连接完成!" << endl;
    return 0;
}

8.STL库

(1)编写程序,利用 string 类提供的成员函数来完成字符串的查找与替换。

#include <iostream>
#include <string>
using namespace std;

void findAndReplace(string& str, const string& oldSubstr, const string& newSubstr) {
    size_t pos = 0;
    while ((pos = str.find(oldSubstr, pos)) != string::npos) {
        str.replace(pos, oldSubstr.length(), newSubstr);
        pos += newSubstr.length(); // 移动到替换后的位置
    }
}

int main() {
    string str;
    string oldSubstr, newSubstr;

    cout << "请输入原始字符串: ";
    getline(cin, str);
    cout << "请输入要查找的子字符串: ";
    getline(cin, oldSubstr);
    cout << "请输入替换的子字符串: ";
    getline(cin, newSubstr);

    findAndReplace(str, oldSubstr, newSubstr);
    
    cout << "替换后的字符串: " << str << endl;

    return 0;
}

(2)编写程序,利用 string 类完成一个字符串的逆序输出。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void reverseString(string& str) {
    reverse(str.begin(), str.end());  // 使用 STL 提供的 reverse 函数
}

int main() {
    string str;
    
    cout << "请输入字符串: ";
    getline(cin, str);

    reverseString(str);
    
    cout << "逆序后的字符串: " << str << endl;

    return 0;
}

(3)编写程序,利用vector 容器输入若干个 string 类数据元素,将其排序后输出。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    vector<string> strVec;
    string str;
    int n;

    cout << "请输入字符串的数量: ";
    cin >> n;
    cin.ignore();  // 忽略前面的换行符

    cout << "请输入 " << n << " 个字符串: " << endl;
    for (int i = 0; i < n; ++i) {
        getline(cin, str);
        strVec.push_back(str);
    }

    sort(strVec.begin(), strVec.end());  // 对 vector 中的字符串进行排序

    cout << "排序后的字符串: " << endl;
    for (const string& s : strVec) {
        cout << s << endl;
    }

    return 0;
}

(4)编写程序,利用输入、输出迭代器,将一个文件中的内容添加到另一个文件的尾部。

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
using namespace std;

void appendFileContents(const string& inputFile, const string& outputFile) {
    ifstream inFile(inputFile);
    ofstream outFile(outputFile, ios::app);  // 以追加模式打开输出文件
    
    if (!inFile) {
        cout << "无法打开输入文件!" << endl;
        return;
    }

    if (!outFile) {
        cout << "无法打开输出文件!" << endl;
        return;
    }

    // 使用输入迭代器读取输入文件内容并使用输出迭代器写入输出文件
    copy(istream_iterator<string>(inFile), istream_iterator<string>(), ostream_iterator<string>(outFile, "\n"));

    inFile.close();
    outFile.close();
}

int main() {
    string inputFile, outputFile;

    cout << "请输入输入文件名: ";
    cin >> inputFile;
    cout << "请输入输出文件名: ";
    cin >> outputFile;

    appendFileContents(inputFile, outputFile);

    cout << "文件内容已成功追加!" << endl;

    return 0;
}

9.异常

(1)编写一个程序,采用异常处理的方法,对数组的标错误进行显示

#include <iostream>
#include <stdexcept>  // 引入 std::out_of_range
using namespace std;

void accessArrayElement(int* arr, int size, int index) {
    if (index < 0 || index >= size) {
        throw out_of_range("数组下标越界错误!");
    }
    cout << "数组元素: " << arr[index] << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    int index;
    cout << "请输入数组下标: ";
    cin >> index;

    try {
        accessArrayElement(arr, size, index);
    } catch (const out_of_range& e) {
        cout << "错误: " << e.what() << endl;
    }

    return 0;
}

(2)编写一个程序,采用异常处理的方法,在指定文件不存在时显示出错信息,文件存在时显示文件的基本信息。

#include <iostream>
#include <fstream>
#include <stdexcept>  // 引入 std::ifstream 和 std::runtime_error
#include <string>
using namespace std;

void checkFileExistence(const string& filename) {
    ifstream file(filename);
    if (!file) {
        throw runtime_error("文件不存在或无法打开!");
    }

    string line;
    cout << "文件存在!文件内容如下:" << endl;

    // 显示文件的基本信息(这里只是显示文件内容示例)
    while (getline(file, line)) {
        cout << line << endl;
    }
    file.close();
}

int main() {
    string filename;
    cout << "请输入文件名: ";
    cin >> filename;

    try {
        checkFileExistence(filename);
    } catch (const runtime_error& e) {
        cout << "错误: " << e.what() << endl;
    }

    return 0;
}

10.基础分支

(1)编写程序,提示用户输入三角形的三条边长,判断该三角形是否为直角三角形,若是则输出结果以及三角形面积。

#include <iostream>
#include <cmath>
using namespace std;

bool isRightTriangle(double a, double b, double c) {
    // 判断是否为直角三角形
    return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a);
}

double areaOfTriangle(double a, double b, double c) {
    // 使用海伦公式计算三角形面积
    double s = (a + b + c) / 2;  // 半周长
    return sqrt(s * (s - a) * (s - b) * (s - c));  // 面积
}

int main() {
    double a, b, c;
    
    cout << "请输入三角形的三条边长: ";
    cin >> a >> b >> c;

    // 判断是否为直角三角形
    if (isRightTriangle(a, b, c)) {
        cout << "该三角形是直角三角形!" << endl;
        double area = areaOfTriangle(a, b, c);
        cout << "直角三角形的面积为: " << area << endl;
    } else {
        cout << "该三角形不是直角三角形!" << endl;
    }

    return 0;
}

(2)编写程序,求解各种数据类型的存储长度并显示出来,在其中找出存储长度最大和最小的两种数据类型并输出。

#include <iostream>
#include <climits>  // 提供数据类型的限制
using namespace std;

int main() {
    cout << "数据类型的存储长度(单位:字节):" << endl;
    
    cout << "char: " << sizeof(char) << " byte(s)" << endl;
    cout << "short: " << sizeof(short) << " byte(s)" << endl;
    cout << "int: " << sizeof(int) << " byte(s)" << endl;
    cout << "long: " << sizeof(long) << " byte(s)" << endl;
    cout << "long long: " << sizeof(long long) << " byte(s)" << endl;
    cout << "float: " << sizeof(float) << " byte(s)" << endl;
    cout << "double: " << sizeof(double) << " byte(s)" << endl;
    cout << "long double: " << sizeof(long double) << " byte(s)" << endl;

    // 找出最大和最小的存储长度
    size_t maxSize = 0, minSize = SIZE_MAX;
    string maxType, minType;

    // 比较不同数据类型的大小
    if (sizeof(char) < minSize) { minSize = sizeof(char); minType = "char"; }
    if (sizeof(short) < minSize) { minSize = sizeof(short); minType = "short"; }
    if (sizeof(int) < minSize) { minSize = sizeof(int); minType = "int"; }
    if (sizeof(long) < minSize) { minSize = sizeof(long); minType = "long"; }
    if (sizeof(long long) < minSize) { minSize = sizeof(long long); minType = "long long"; }
    if (sizeof(float) < minSize) { minSize = sizeof(float); minType = "float"; }
    if (sizeof(double) < minSize) { minSize = sizeof(double); minType = "double"; }
    if (sizeof(long double) < minSize) { minSize = sizeof(long double); minType = "long double"; }

    if (sizeof(char) > maxSize) { maxSize = sizeof(char); maxType = "char"; }
    if (sizeof(short) > maxSize) { maxSize = sizeof(short); maxType = "short"; }
    if (sizeof(int) > maxSize) { maxSize = sizeof(int); maxType = "int"; }
    if (sizeof(long) > maxSize) { maxSize = sizeof(long); maxType = "long"; }
    if (sizeof(long long) > maxSize) { maxSize = sizeof(long long); maxType = "long long"; }
    if (sizeof(float) > maxSize) { maxSize = sizeof(float); maxType = "float"; }
    if (sizeof(double) > maxSize) { maxSize = sizeof(double); maxType = "double"; }
    if (sizeof(long double) > maxSize) { maxSize = sizeof(long double); maxType = "long double"; }

    cout << "\n存储长度最小的数据类型: " << minType << " (" << minSize << " byte(s))" << endl;
    cout << "存储长度最大的 数据类型: " << maxType << " (" << maxSize << " byte(s))" << endl;

    return 0;
}

(3)编写程序输入一个华氏温度,将其转换为摄氏温度并输出。已知华氏温度转换为摄氏温度的计算公式如下:
C=(F-32)*5/9
其中,F 为华氏温度,C为摄氏温度。

#include <iostream>
using namespace std;

int main() {
    double fahrenheit, celsius;
    
    cout << "请输入华氏温度: ";
    cin >> fahrenheit;

    // 华氏温度转摄氏温度
    celsius = (fahrenheit - 32) * 5 / 9;

    cout << "对应的摄氏温度为: " << celsius << "°C" << endl;

    return 0;
}

(4)编写程序输入一个十进制表示的正整数,将其转化为二进制表示并输出结果。

#include <iostream>
#include <stack>
using namespace std;

void decimalToBinary(int n) {
    stack<int> binaryStack;
    
    while (n > 0) {
        binaryStack.push(n % 2);
        n = n / 2;
    }

    cout << "二进制表示: ";
    while (!binaryStack.empty()) {
        cout << binaryStack.top();
        binaryStack.pop();
    }
    cout << endl;
}

int main() {
    int num;

    cout << "请输入一个十进制正整数: ";
    cin >> num;

    if (num <= 0) {
        cout << "请输入一个正整数!" << endl;
    } else {
        decimalToBinary(num);
    }

    return 0;
}

11.基础循环

(1)编写程序,计算1~100所有3的倍数的数的和。

#include <iostream>
using namespace std;

int main() {
    int sum = 0;

    for (int i = 1; i <= 100; i++) {
        if (i % 3 == 0) {
            sum += i;
        }
    }

    cout << "1~100 所有 3 的倍数的和是: " << sum << endl;

    return 0;
}

(2)编写程序,用户输入一些整数,该程序分别计算出所有奇数和所有偶数之和,并输出它们。

#include <iostream>
using namespace std;

int main() {
    int num;
    int oddSum = 0, evenSum = 0;

    cout << "请输入整数,输入 0 结束: ";
    while (true) {
        cin >> num;
        if (num == 0) break;
        
        if (num % 2 == 0) {
            evenSum += num;
        } else {
            oddSum += num;
        }
    }

    cout << "奇数和: " << oddSum << endl;
    cout << "偶数和: " << evenSum << endl;

    return 0;
}

(3)编写程序,求解输入两个正整数的最大公约数和最小公倍数。

#include <iostream>
using namespace std;

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b) {
    return (a * b) / gcd(a, b);
}

int main() {
    int a, b;
    
    cout << "请输入两个正整数: ";
    cin >> a >> b;

    cout << "最大公约数: " << gcd(a, b) << endl;
    cout << "最小公倍数: " << lcm(a, b) << endl;

    return 0;
}

(4)编写程序计算10个正整数的平均值、方差以及标准方差。

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int numbers[10];
    int sum = 0;

    cout << "请输入 10 个正整数: ";
    for (int i = 0; i < 10; i++) {
        cin >> numbers[i];
        sum += numbers[i];
    }

    double mean = sum / 10.0;

    double variance = 0;
    for (int i = 0; i < 10; i++) {
        variance += pow(numbers[i] - mean, 2);
    }
    variance /= 10;

    double stdDeviation = sqrt(variance);

    cout << "平均值: " << mean << endl;
    cout << "方差: " << variance << endl;
    cout << "标准方差: " << stdDeviation << endl;

    return 0;
}

(5)输入4个字母,并反向显示这些字母。

#include <iostream>
using namespace std;

int main() {
    char letters[4];

    cout << "请输入 4 个字母: ";
    for (int i = 0; i < 4; i++) {
        cin >> letters[i];
    }

    cout << "反向显示字母: ";
    for (int i = 3; i >= 0; i--) {
        cout << letters[i];
    }
    cout << endl;

    return 0;
}

(6)输出所有的“水仙花数”。“水仙花数”是指一个3位数,其各位数字的立方和等于该数本身。例如,153 为一个水仙花数,因为153=1+5+3。

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "所有水仙花数: ";
    for (int i = 100; i < 1000; i++) {
        int hundreds = i / 100;
        int tens = (i / 10) % 10;
        int ones = i % 10;

        if (pow(hundreds, 3) + pow(tens, 3) + pow(ones, 3) == i) {
            cout << i << " ";
        }
    }
    cout << endl;

    return 0;
}

(7)求∑n!(即 1!+2!+…+50!)。

#include <iostream>
using namespace std;

long long factorial(int n) {
    long long result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

int main() {
    long long sum = 0;
    for (int i = 1; i <= 50; i++) {
        sum += factorial(i);
    }

    cout << "1! + 2! + ... + 50! 的和为: " << sum << endl;

    return 0;
}

(8)编写程序求一元二次方程 ax’+bx+c=0 的解。
该方程的解分为以下几种情况:
① b-4ac=0,有两个相等的实根;

② b’-4ac>0,有两个不等的实根;
③ b’-4ac<0,无实根:
④ a=0,不是二次方程。

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double a, b, c;
    cout << "请输入一元二次方程的系数 a, b, c: ";
    cin >> a >> b >> c;

    if (a == 0) {
        cout << "这不是一元二次方程!" << endl;
        return 0;
    }

    double discriminant = b * b - 4 * a * c;  // 判别式

    if (discriminant > 0) {
        double root1 = (-b + sqrt(discriminant)) / (2 * a);
        double root2 = (-b - sqrt(discriminant)) / (2 * a);
        cout << "方程有两个不等的实根: " << root1 << " 和 " << root2 << endl;
    } else if (discriminant == 0) {
        double root = -b / (2 * a);
        cout << "方程有两个相等的实根: " << root << endl;
    } else {
        cout << "方程没有实根!" << endl;
    }

    return 0;
}

(9)编写程序,用循环语句打印如下图案。

(10)编写程序,输入年月日信息,并输出这一天为这一年的第几天,注意闰年问题。

#include <iostream>
using namespace std;

// 函数声明
bool isLeapYear(int year);
int dayOfYear(int year, int month, int day);

int main() {
    int year, month, day;
    
    // 输入年月日
    cout << "请输入年月日(格式:年 月 日):";
    cin >> year >> month >> day;
    
    // 计算并输出结果
    int result = dayOfYear(year, month, day);
    cout << year << "年" << month << "月" << day << "日是这一年的第" << result << "天" << endl;
    
    return 0;
}

// 判断是否为闰年
bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 计算某一天是该年的第几天
int dayOfYear(int year, int month, int day) {
    // 每月天数数组,索引0不用
    int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    // 如果是闰年,二月有29天
    if (isLeapYear(year)) {
        daysInMonth[2] = 29;
    }
    
    int totalDays = 0;
    
    // 累加前几个月的天数
    for (int i = 1; i < month; i++) {
        totalDays += daysInMonth[i];
    }
    
    // 加上当前月的天数
    totalDays += day;
    
    return totalDays;
}

(11)编写程序,由用户输入x值,计算函数值并输出。函数如下所示。

(12)鸡兔同笼问题。若鸡免共有100只脚,利用循环计算鸡兔各几只。

#include <iostream>
using namespace std;

int main() {
    int totalFeet = 100;
    
    cout << "鸡兔同笼问题(总脚数100):" << endl;
    cout << "可能的解有:" << endl;
    
    // 循环遍历可能的鸡的数量
    for (int chicken = 0; chicken <= 50; chicken++) {
        int rabbit = (totalFeet - 2 * chicken) / 4;
        
        // 检查是否满足条件:总脚数为100,且鸡兔数量均为非负整数
        if (2 * chicken + 4 * rabbit == totalFeet && rabbit >= 0) {
            cout << "鸡:" << chicken << "只,兔:" << rabbit << "只" << endl;
        }
    }
    
    return 0;
}