C ++程序将时间从12小时转换为24小时格式
这是一个C++程序,用于将时间从12小时转换为24小时格式。
算法
Begin
In main(),
If median = pm
Check if entered hours is less than 12
Then add 12 to hours and print the time in 24 hours format.
Check if entered hours is equal to 12
Then print “00” as hours and print the time in 24 hours format.
Else If median=am
Check if entered hours is less than 12
Then print the time in 24 hours format.
Check if entered hours is equal to 12
Then print “12” as hours and print the time in 24 hours format.
Else print wrong choice.
End示例
#include<iostream>
#include<string.h>
#include <iomanip>
using namespace std;
int main() {
int hours,minutes,seconds,h1,m1,s1;
char median[10];
cout<<"Enter hours, minutes, seconds:";
cin>>hours;
cin>>minutes;
cin>>seconds;
cout<<"输入中位数:";
cin>>median;
cout<<"时间以12小时格式:"<<setfill('0') << setw(2) <<hours<<":"<<setfill('0') << setw(2)
<<minutes<<":"<<setfill('0') << setw(2) <<seconds<<median<<endl; //setw()=sets the field width,
//setfill()=将字符设置为流填充字符。
if(strcmp(median,"pm")==0) { //compare the strings "0" is for true "1" is for false.
if (hours<12) {
h1=hours+12;
m1=minutes;
s1=seconds;
cout<<"24小时制的时间:" <<h1<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
} else if(hours=12) {
h1=12;
m1=minutes;
s1=seconds;
cout<<"24小时制的时间:"<<h1<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
}
} else if(strcmp(median,"am")==0) {
if (hours<12) {
h1=hours;
m1=minutes;
s1=seconds;
cout<<"24小时制的时间:"<<setfill('0') << setw(2) <<h1<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
} else if(hours=12) {
m1=minutes;
s1=seconds;
cout<<"24小时制的时间:"<<"00"<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
}
} else {
printf("Wrong choice");
}
}输出结果
Enter hours, minutes, seconds:12 07 06 输入中位数:pm 时间以12小时格式:12:07:06pm 24小时制的时间:12:07:06pm Enter hours, minutes, seconds:01 02 30 输入中位数:pm 时间以12小时格式:01:02:30pm 24小时制的时间:13:2:30pm Enter hours, minutes, seconds:10 10 03 输入中位数:am 时间以12小时格式:10:10:03am 24小时制的时间:10:10:03am Enter hours, minutes, seconds:12 02 04 输入中位数:am 时间以12小时格式:12:02:04am 24小时制的时间:00:02:04am
热门推荐
7 入学校简短祝福语
10 同事们生日祝福语简短
11 朋友弟弟生日祝福语简短
12 生日祝福语古朴简短独特
13 阳历新年祝福语大全 简短
14 圣诞简短祝福语给父母
15 送给情侣贺卡祝福语简短
16 打游戏通关祝福语简短
17 白羊生日祝福语 简短独特
18 表妹结婚祝福语简短藏语