计算机二级备考

发布于:2025-03-09 ⋅ 阅读:(14) ⋅ 点赞:(0)

1.头文件和命名空间

#include <iostream>//包含标准输入输出流库,用于使用cout和cin进行控制台输入输出。
#include <cmath>//包含数学库,这里虽然代码中未直接使用,但可能后续扩展会用到相关数学函数。
#include <fstream>//包含文件流库,用于文件的读写操作。
#include <string>//包含字符串库,用于处理字符串类型的数据。
using namespace std;//使用标准命名空间,这样可以直接使用标准库中的类和函数,而无需添加std::前缀。

 2.

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

// 定义FlowerNumber类,用于计算指定范围内的花朵数
class FlowerNumber {
public:
    // 构造函数,初始化最小值、最大值和计数,用于初始化min、max和count,min和max表示待计算的数值范围,count用于记录花朵数的数量。
    FlowerNumber(int x1, int x2) : min(x1), max(x2), count(0) {}

    // 计算数字x的位数
    int GetDigits(int x);

    // 重置计数
    void ResetCount() { count = 0; }

    // 获取当前花朵数的数量
    int GetCount() const { return count; }

    // 获取集合中指定索引位置的花朵数
    int GetSet(int index) { return set[index]; }

    // 计算指定范围内的花朵数
    void Flower();

    // 打印指定范围内的花朵数信息
    void Print() {
        cout << min << "和" << max << "之间的花朵数共有" << count << "个:" << endl;
        for (int i = 0; i < count; i++)
            cout << set[i] << ' ';
        cout << endl;
    }

private:
    int digit;  // 花朵数的位数
    int min, max;  // 待计算的数值范围
    int count;  // 花朵数的数量
    int set[40];  // 花朵数集合
};

// 实现GetDigits函数,计算数字x的位数
int FlowerNumber::GetDigits(int x) {
    int i;
    for (i = 0; x > 0; i++)
        x /= 10;
    return i;
}

// 实现Flower函数,计算指定范围内的花朵数
void FlowerNumber::Flower() {
    int sum = 0;//声明一个整数变量sum并初始化为0,用于存储各位数字的幂次方和。

    // 遍历从min到max的所有整数
    for (int i = min; i <= max; i++) {//使用for循环遍历从min到max(包含min和max)的所有整数。
        int t = i, p = 1, r;//声明变量t,并将当前循环变量i的值赋给t,用于后续分解各位数字。声明变量p并初始化为1,用于计算各位数字的幂次方。声明变量r,用于存储t的最后一位数字。
        // 获取当前数字i的位数,并将结果存储在变量digit中,GetDigits函数的作用是计算一个数字的位数
        digit = GetDigits(i);
        sum = 0;  // 在每次循环开始时,将sum重置为0,以便重新计算当前数字的各位数字的幂次方和。
        while (t) {//这个循环的目的是分解数字t的每一位,并计算它们的幂次方和。
            p = 1;//在每次循环迭代开始时,将p重置为1,用于计算当前位数字的幂次方。
            
            r = t % 10;// 使用取模运算符%获取t的最后一位数字,并存储在变量r中。
            if (r == 0)//如果最后一位数字r是0,则将p设置为0。是因为0的任何次幂都是0,所以直接跳过计算
                p = 0;
            else {
                //计算r的digit次幂。
                for (int j = 0; j < digit; j++)
                    p = p * r;
            }
            sum += p;
            t = t / 10;  // 去掉t的最后一位数字
        }
        // 检查sum是否等于当前数字i。如果相等,说明i是一个水仙花数(Flower Number),将其存储到数组set中,并将count递增1。
        if (sum == i)
            set[count++] = i;
    }
}

// 将花朵数信息写入文件的函数
void writeToFile(const string filename) {
    ofstream outFile(filename);
    if (outFile.is_open()) {
        // 这里可以添加将花朵数信息写入文件的逻辑
        outFile.close();
    } else {
        cerr << "无法打开文件" << endl;
    }
}

int main() {
    int d1, d2;
    cout << "请输入整数序列范围,以两个整数表示,空格为分隔符,回车键结束:";
    cin >> d1 >> d2;
    // 创建FlowerNumber对象
    FlowerNumber obj(d1, d2);
    // 调用Flower函数计算花朵数
    obj.Flower();
    // 调用Print函数打印花朵数信息
    obj.Print();
    // 调用writeToFile函数将花朵数信息写入文件
    writeToFile("");
    return 0;
}