You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用time.h库实现2分钟循环输出Hello World失败求助

问题分析与修复方案

你的代码有几个关键问题导致它无法正常工作,我来逐个拆解并给出修复方案:

核心问题点

  • 未初始化变量:temps在第一次使用前没有被赋值,这会导致未定义行为,程序可能出现奇怪的结果。
  • 错误的循环条件:你的循环条件是判断当前CPU时间刚好等于设定的秒数,这几乎不可能触发——程序执行速度很快,CPU时间会跳过这个相等的瞬间,导致循环要么直接退出(如果初始CPU时间就超过目标),要么无限运行。
  • CPU时间 vs 实际时间:clock()返回的是程序占用的CPU时钟周期,换算成的是CPU工作时间,不是真实的墙上时间。如果程序被系统调度暂停,CPU时间不会增加,但实际时间仍在流逝,这会导致计时不准。

修复后的代码(C++98兼容版本)

如果需要兼容旧标准,我们可以用time()函数来获取实际时间,同时修正循环逻辑:

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

int main(int argc, char const *argv[]) {
    int gameTimeMinutes;
    cout << "Insert the time (minute) : ";
    cin >> gameTimeMinutes;
    
    time_t startTime = time(NULL); // 获取开始时间
    int gameTimeSeconds = gameTimeMinutes * 60;

    do {
        cout << "Hello world !" << endl;
        // 可选:每次输出后短暂休眠,避免疯狂刷屏占用资源
        // Sleep(1000); // Windows下,单位毫秒
        // usleep(1000000); // Linux/macOS下,单位微秒(1秒=1e6微秒)
    } while (difftime(time(NULL), startTime) < gameTimeSeconds); // 判断是否未到时间

    return 0;
}

更现代的C++11+方案(推荐)

用std::chrono库可以更精确、类型安全地处理时间:

#include <iostream>
#include <chrono>
#include <thread> // 用于sleep_for
using namespace std;

int main() {
    int gameTimeMinutes;
    cout << "Insert the time (minute) : ";
    cin >> gameTimeMinutes;
    
    auto startTime = chrono::steady_clock::now();
    auto duration = chrono::minutes(gameTimeMinutes);

    do {
        cout << "Hello world !" << endl;
        // 每秒输出一次,避免刷屏
        this_thread::sleep_for(chrono::seconds(1));
    } while (chrono::steady_clock::now() - startTime < duration);

    return 0;
}

额外建议

  • 如果不想疯狂输出刷屏,一定要加上休眠逻辑(上面代码里的注释部分),否则程序会在2分钟内输出几十万次"Hello world!",既占用CPU资源,也看不清输出内容。
  • chrono::steady_clock是最适合计时的时钟,它不会因为系统时间调整而变化,比system_clock更可靠。

内容的提问来源于stack exchange,提问作者K.J Fogang Fokoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:36:59