C++代码题部分(1)

发布于:2025-07-31 ⋅ 阅读:(16) ⋅ 点赞:(0)

3.编程

3.1 实现一个函数可以打印下列数组的元素

测试用例 1
int main()
{
    int ar[]={1,2,3,4,5,6};
    double dr[]={12.23,34.45,56.67};
    char str[]={"yhping"};
    PrintAr(ar);
    PrintAr(dr);
    PrintAr(str);
    return 0;
}

测试用例 2
struct Student
{
    char s_name[20];
    int s_age;
};
int main()
{
    Student sar[]={{"yhping",12},{"tulun",23},{"yuntu",16}};
    PrintAr(sar);
    return 0;
}

分析与实现:需实现模板函数 PrintAr,根据不同类型数组(基本类型数组、自定义结构体数组 )打印元素。利用 C++ 模板特性,自动适配不同类型。

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

// 处理基本类型数组
template <typename T>
void PrintAr(T arr[], int size) {
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// 处理 Student 结构体数组(也可通过模板特化更通用处理,这里简化演示 )
template <>
void PrintAr(Student arr[], int size) {
    for (int i = 0; i < size; ++i) {
        cout << "Name: " << arr[i].s_name << ", Age: " << arr[i].s_age << endl;
    }
}

// 辅助函数,获取数组长度(针对静态数组,动态数组需传长度 )
template <typename T, int N>
int getArraySize(T (&arr)[N]) {
    return N;
}

int main()
{
    int ar[] = {1,2,3,4,5,6};
    double dr[] = {12.23,34.45,56.67};
    char str[] = {"yhping"};
    // 调用时通过辅助函数传数组长度,或手动指定
    PrintAr(ar, getArraySize(ar));
    PrintAr(dr, getArraySize(dr));
    PrintAr(str, getArraySize(str));

    Student sar[] = {{"yhping",12},{"tulun",23},{"yuntu",16}};
    PrintAr(sar, getArraySize(sar));
    return 0;
}

3.2 输入年月日时分秒

void PrintDate(const std::string &str)
{
    cout<<str<<endl; //显示为2022/09/19 02:07:48
}
int main()
{
    const string datetime;
    int year,month,day;
    int hour,minutes,seconds;
    cin>>year>>month>>day>>hour>>minutes>>seconds;
    //补充代码
    PrintDate(da);
    return 0;
}

需求扩展

  • 调用标准库 API 函数获取时间,打印为本地的日期和时间,格式同上
  • 调用标准库 API 函数获取时间,打印本世界标准时间 (UTC),格式同上
  • 探究是否可以获得高精度的时间,如:微秒或纳秒级别
  • 区分 time 与 clock 函数
    • time 函数:返回纪元开始经过的当前系统日历时间,从 UTC 1970 年 1 月 1 日 00:00 开始秒数的整数值
    • clock 函数:程序迄今为止所用的处理器时间(cup 时钟计时器所经过的时钟周期数 )。

实现代码

#include <iostream>
#include <string>
#include <ctime>
#include <sstream>
#include <<iomanip>
using namespace std;

void PrintDate(const string &str) {
    cout << str << endl;
}

// 格式化时间为字符串,支持本地时间和 UTC 时间
string formatTime(tm *timeInfo, bool isUTC = false) {
    ostringstream oss;
    oss << setfill('0') << timeInfo->tm_year + 1900 << "/" 
        << setw(2) << timeInfo->tm_mon + 1 << "/" 
        << setw(2) << timeInfo->tm_mday << " " 
        << setw(2) << timeInfo->tm_hour << ":" 
        << setw(2) << timeInfo->tm_min << ":" 
        << setw(2) << timeInfo->tm_sec;
    return oss.str();
}

int main()
{
    // 手动输入年月日时分秒场景
    const string datetime;
    int year, month, day;
    int hour, minutes, seconds;
    cout << "请输入年月日时分秒(空格分隔):";
    cin >> year >> month >> day >> hour >> minutes >> seconds;
    
    tm inputTime = {};
    inputTime.tm_year = year - 1900;
    inputTime.tm_mon = month - 1;
    inputTime.tm_mday = day;
    inputTime.tm_hour = hour;
    inputTime.tm_min = minutes;
    inputTime.tm_sec = seconds;
    // 转换为时间戳(假设输入合法,实际需校验 )
    time_t inputTimeStamp = mktime(&inputTime);
    tm *localTime = localtime(&inputTimeStamp);
    tm *utcTime = gmtime(&inputTimeStamp);
    PrintDate(formatTime(localTime)); 
    PrintDate(formatTime(utcTime, true)); 

    // 获取当前系统本地时间和 UTC 时间
    time_t now = time(nullptr);
    tm *localNow = localtime(&now);
    tm *utcNow = gmtime(&now);
    cout << "当前本地时间:" << formatTime(localNow) << endl;
    cout << "当前 UTC 时间:" << formatTime(utcNow, true) << endl;

    // 高精度时间(C++11 及以上,利用 <chrono> )
    #if __cplusplus >= 201103L
    #include <chrono>
    auto nowHighRes = chrono::high_resolution_clock::now();
    auto duration = nowHighRes.time_since_epoch();
    long long microseconds = chrono::duration_cast<chrono::microseconds>(duration).count();
    long long nanoseconds = chrono::duration_cast<chrono::nanoseconds>(duration).count();
    cout << "高精度时间(微秒):" << microseconds << " 微秒" << endl;
    cout << "高精度时间(纳秒):" << nanoseconds << " 纳秒" << endl;
    #else
    cout << "编译器不支持 C++11 及以上,无法演示高精度时间获取" << endl;
    #endif

    // 区分 time 和 clock 函数
    time_t te = time(nullptr);
    clock_t ck = clock();
    cout << "time 函数获取的时间戳:" << te << " 秒(纪元到当前系统日历时间 )" << endl;
    cout << "clock 函数获取的处理器时间:" << ck << " tick 数(程序所用处理器时间 )" << endl;

    return 0;
}

3.3 输入数字,输出对应的字符串

typedef enum LOG_LEVEL
{
    TRACE = 0, // 跟踪,追踪
    DEBUG,     // 调试
    INFO,      // 信息
    WARN,      // 警告
    ERROR,     // 错误
    FATAL,     // 致命错误
    NUM_LOG_LEVELS, // 日志级别数
} LOG_LEVEL;

需求:输入数字(如 0 输出 "TRACE",2 输出 "INFO" ),输出对应的字符串。

实现代码

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

typedef enum LOG_LEVEL
{
    TRACE = 0,   // 跟踪,追踪
    DEBUG,       // 调试
    INFO,        // 信息
    WARN,        // 警告
    ERROR,       // 错误
    FATAL,       // 致命错误
    NUM_LOG_LEVELS, // 日志级别数
} LOG_LEVEL;

string getLogLevelStr(LOG_LEVEL level) {
    switch (level) {
        case TRACE:   return "TRACE";
        case DEBUG:   return "DEBUG";
        case INFO:    return "INFO";
        case WARN:    return "WARN";
        case ERROR:   return "ERROR";
        case FATAL:   return "FATAL";
        default:      return "UNKNOWN";
    }
}

int main() {
    int input;
    cout << "请输入日志级别数字(0 - " << NUM_LOG_LEVELS - 1 << "):";
    cin >> input;
    if (input < 0 || input >= NUM_LOG_LEVELS) {
        cout << "输入无效,范围应为 0 到 " << NUM_LOG_LEVELS - 1 << endl;
        return 1;
    }
    LOG_LEVEL level = static_cast<LOG_LEVEL>(input);
    cout << "对应的字符串:" << getLogLevelStr(level) << endl;
    return 0;
}

3.4 动态创建二维数组

需求:输入行和列值,动态构建二维数组。

实现代码

#include <iostream>
using namespace std;

int** create2DArray(int rows, int cols) {
    int** arr = new int*[rows];
    for (int i = 0; i < rows; ++i) {
        arr[i] = new int[cols];
        // 可初始化,如初始化为 0
        for (int j = 0; j < cols; ++j) {
            arr[i][j] = 0;
        }
    }
    return arr;
}

void delete2DArray(int** arr, int rows) {
    for (int i = 0; i < rows; ++i) {
        delete[] arr[i];
    }
    delete[] arr;
}

int main() {
    int rows, cols;
    cout << "请输入二维数组的行数和列数(空格分隔):";
    cin >> rows >> cols;
    
    int** arr = create2DArray(rows, cols);
    // 测试赋值
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            arr[i][j] = i * cols + j; 
        }
    }
    // 打印二维数组
    cout << "动态创建的二维数组:" << endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    delete2DArray(arr, rows);
    return 0;
}

网站公告

今日签到

点亮在社区的每一天
去签到