洛谷

随机数

#include <iostream>
#include <vector>
#include <cstdlib>  // 包含rand()和srand()
#include <ctime>    // 包含time()

int main() {
    // 待抽取的列表
    std::vector<int> nums = {1, 3, 5, 7, 9, 11, 13};

    // 初始化随机数种子(用当前时间,确保每次运行结果不同)
    srand(time(0));

    // 生成随机索引(范围:0 到 列表大小-1)
    int randomIndex = rand() % nums.size();

    // 输出随机选中的元素
    std::cout << "随机选中的元素:" << nums[randomIndex] << std::endl;

    return 0;
}
#include <iostream>
#include <cstdlib>  // 包含rand()和srand()
#include <ctime>    // 包含time()

int main() {
    // 定义数组并初始化
    int nums[] = {2, 4, 6, 8, 10, 12};
    // 计算数组元素个数(总字节数 / 单个元素字节数)
    int count = sizeof(nums) / sizeof(nums[0]);

    // 用当前时间初始化随机数种子,确保每次结果不同
    srand((unsigned int)time(NULL));

    // 生成0到count-1之间的随机索引
    int randomIndex = rand() % count;

    // 输出随机选中的元素
    std::cout << "随机选中的元素:" << nums[randomIndex] << std::endl;

    return 0;
}