編寫一個使用 if 和 elseif 語句進行時間轉換的 C 語言程式


問題

如何使用 C 語言程式設計將時間從 24 小時制轉換為 12 小時制?

解決方案

從使用者讀取時間值(執行時)。它必須從 24 小時制轉換為 12 小時制。

演算法

Start:
Step 1: Enter time in 24 hr format
Step 2: check the condition
      i. If(hour==0)
         Print min
     Ii. Elseif(hour<12)
          Print hour,min
    iii. Elseif(hour==12
         Print hour,min
     iv. Else
         Print hour % 12,min
Stop:

程式

 線上演示

#include<stdio.h>
int main(){
   int hr,min;
   printf("enter the time in 24 hour format:");
   scanf("%d:%d",&hr,&min);
   printf("The 12 hr format time:");
   if(hr==0){
      printf("12:%.2d AM
",min);    }    else if(hr<12){       printf("%d:%.2d AM
",hr,min);    }    else if(hr==12){       printf("%d:%.2d PM
",hr,min);    }    else       printf("%d:%.2d PM
",hr % 12,min);    return 0; }

輸出

enter the time in 24 hour format:22:37
The 12 hr format time:10:37 PM

更新於: 2021 年 3 月 5 日

1K+ 檢視

開啟你的 職業生涯

完成課程後獲取認證

開始
廣告
© . All rights reserved.