Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

시간을 12시간에서 24시간 형식으로 변환하는 C++ 프로그램

<시간/>

시간을 12시간에서 24시간 형식으로 변환하는 C++ 프로그램입니다.

알고리즘

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<<"Enter median:";
   cin>>median;
   cout<<"Time in 12 hour format:"<<setfill('0') << setw(2) <<hours<<":"<<setfill('0') << setw(2)
   <<minutes<<":"<<setfill('0') << setw(2) <<seconds<<median<<endl; //setw()=sets the field width,
   //setfill()=set character as the streams fill character.
   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<<"Time in 24 hour format:" <<h1<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
      } else if(hours=12) {
         h1=12;
         m1=minutes;
         s1=seconds;
         cout<<"Time in 24 hour format:"<<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<<"Time in 24 hour format:"<<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<<"Time in 24 hour format:"<<"00"<<":"<<setfill('0') << setw(2) <<m1<<":"<<setfill('0') << setw(2) <<s1<<median;
      }
   } else {
      printf("Wrong choice");
   }
}

출력

Enter hours, minutes, seconds:12
07
06
Enter median:pm
Time in 12 hour format:12:07:06pm
Time in 24 hour format:12:07:06pm

Enter hours, minutes, seconds:01
02
30
Enter median:pm
Time in 12 hour format:01:02:30pm
Time in 24 hour format:13:2:30pm

Enter hours, minutes, seconds:10
10
03
Enter median:am
Time in 12 hour format:10:10:03am
Time in 24 hour format:10:10:03am

Enter hours, minutes, seconds:12
02
04
Enter median:am
Time in 12 hour format:12:02:04am
Time in 24 hour format:00:02:04am