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

军事时间转常规时间:如何补全分钟位的前导零?

军事时间转常规时间:分钟位前导零缺失问题解决

问题:实现C++程序将军事时间转为常规时间时,分钟为个位数无法显示前导零,例如输入0000得到12:0 AM,输入608得到6:8 AM,需要修复该问题。相关代码如下:

main.cc

#include "time_converter.h"
#include <iostream>

int main() {
  int military_time;
  std::cout << "Please enter the time in military time: ";
  std::cin >> military_time;
  
  std::string regular_time;
  regular_time = MilitaryToRegularTime(military_time);

  std::cout << "The equivalent regular time is: " << regular_time << "\n";
  return 0;
}

time_converter.h

#include <iostream>

// Converts the time in military format to regular format.
std::string MilitaryToRegularTime(int military_time);

time_converter.cc

#include <iostream>

std::string amorpm;
std::string MilitaryToRegularTime(int military_time) {
  int regular_hr = military_time / 100;
  if (regular_hr >= 13){
     regular_hr = (military_time / 100) - 12;
  }
  
  if (regular_hr == 0){
    regular_hr = 12;
  }
 
  int regular_min = military_time % 100;
  
  if (military_time >= 1200 && military_time <= 2359){
    amorpm = " PM\n";
  }
  if (military_time >= 0000 && military_time <= 1159 ){
    amorpm = " AM\n";
  }

  std::string regular_hr_str = std::to_string(regular_hr);
  std::string regular_min_str = std::to_string(regular_min);

  return regular_hr_str + ":" + regular_min_str + amorpm;
}

修复方案

方法1:手动补全前导零

在生成分钟字符串时,判断其长度,若为1位则在前面添加'0':

std::string regular_min_str = std::to_string(regular_min);
if (regular_min_str.length() == 1) {
    regular_min_str = "0" + regular_min_str;
}

替换原代码中对应的行即可,简单直接,适合快速修复。

方法2:使用字符串流格式化(更规范)

利用std::ostringstream结合格式化控制符输出固定长度的分钟,同时将全局变量amorpm改为局部变量,避免全局状态污染:

修改后的time_converter.cc:

#include <iostream>
#include <sstream>
#include <iomanip> // 用于setw和setfill

std::string MilitaryToRegularTime(int military_time) {
  int regular_hr = military_time / 100;
  if (regular_hr >= 13){
     regular_hr = regular_hr - 12;
  }
  
  if (regular_hr == 0){
    regular_hr = 12;
  }
 
  int regular_min = military_time % 100;
  
  std::string amorpm; // 改为局部变量
  if (military_time >= 1200 && military_time <= 2359){
    amorpm = " PM";
  } else { // 用else替代重复判断,提升效率
    amorpm = " AM";
  }

  std::ostringstream oss;
  oss << regular_hr << ":" << std::setw(2) << std::setfill('0') << regular_min << amorpm;
  
  return oss.str();
}
  • std::setw(2)确保输出占2个字符宽度
  • std::setfill('0')指定宽度不足时用'0'填充
  • 将全局变量amorpm改为局部变量,避免多次调用函数时的状态异常

两种方法均可解决分钟位前导零缺失问题,方法2更符合C++格式化规范,同时优化了变量作用域。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:51:33