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

军事时间转标准时间时如何实现分钟数的两位补零输出?

军事时间转标准时间的C++程序修复

问题根源

你遇到的问题是分钟数输出格式不符合要求:当分钟数为0时,整数类型的mins直接输出只会显示单个0,但标准时间要求分钟数必须以两位数字呈现(如00)。比如输入1300时,计算得到mins=0,原代码直接输出就成了1:0 P.M.,而非预期的1:00 P.M.。

解决方案

要让分钟数始终以两位数字显示,不足时补前导0,有两种常用实现方式:

方式1:使用C++流格式化(需引入<iomanip>头文件)

借助setw(2)设置输出宽度为2,setfill('0')指定填充字符为0,强制分钟数按两位格式输出。

方式2:使用C风格printf输出

通过格式控制符%02d直接指定输出两位数字,不足补0,实现更简洁。

修正后的完整代码

方式1(C++流格式化)

#include <iostream>
#include <iomanip> // 必须包含此头文件用于格式化输出
using namespace std;

int main() {
    int mtime, mins, hrs;
    
    cout << "Military to Standard Time" << endl << "Enter time: ";
    cin >> mtime;
    
    if (mtime >= 0 && mtime <= 2400) {
        bool isPM = false;
        // 处理边界时间:2400、1200、0000
        if (mtime == 2400) {
            hrs = 12;
            mins = 0;
            isPM = false;
        } else if (mtime >= 1200) {
            isPM = true;
            hrs = (mtime > 1200) ? (mtime - 1200) / 100 : 12;
            mins = mtime % 100;
        } else {
            isPM = false;
            hrs = mtime / 100;
            hrs = (hrs == 0) ? 12 : hrs;
            mins = mtime % 100;
        }
        
        // 格式化输出分钟数
        cout << hrs << ":" << setw(2) << setfill('0') << mins << " ";
        cout << (isPM ? "P.M." : "A.M.") << endl;
    } else {
        cout << "Error, Please Enter Military Time 0000-2400" << endl;
    }
    return 0;
}

方式2(printf格式化)

#include <iostream>
using namespace std;

int main() {
    int mtime, mins, hrs;
    
    cout << "Military to Standard Time" << endl << "Enter time: ";
    cin >> mtime;
    
    if (mtime >= 0 && mtime <= 2400) {
        bool isPM = false;
        // 处理边界时间:2400、1200、0000
        if (mtime == 2400) {
            hrs = 12;
            mins = 0;
            isPM = false;
        } else if (mtime >= 1200) {
            isPM = true;
            hrs = (mtime > 1200) ? (mtime - 1200) / 100 : 12;
            mins = mtime % 100;
        } else {
            isPM = false;
            hrs = mtime / 100;
            hrs = (hrs == 0) ? 12 : hrs;
            mins = mtime % 100;
        }
        
        // 用printf格式化输出,%02d保证分钟数为两位
        printf("%d:%02d %s\n", hrs, mins, isPM ? "P.M." : "A.M.");
    } else {
        cout << "Error, Please Enter Military Time 0000-2400" << endl;
    }
    return 0;
}

额外修复说明

原代码还存在边界时间处理错误,修正代码已同步解决:

  • 输入1200时,原代码输出0:00 P.M.,修正后输出12:00 P.M.
  • 输入0000时,原代码输出0:00 A.M.,修正后输出12:00 A.M.
  • 输入2400时,原代码输出0:00 P.M.,修正后输出12:00 A.M.

内容的提问来源于stack exchange,提问作者Pirgor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:40:18