C++24小时制转换成12小时制

英文题目(老师给的原版题目):

Write a program that converts from 24-hour notation to 12-hour notation.For example,it should convert 14:25 to 2:25 PM.The input is given as two integers.There should be at least three functions,one for input,one to do the conversion,and one for output.Record the AM/PM information as a value of type char,’A’ for AM and ‘P’ for PM.Thus,the function for doing the conversions will have a call-by-reference formal parameter of type char to record whether it is AM or PM.(The function will have other parameters as well.)Include a loop that lets the user repeat this computation for new input values again and again until the user says he wants to end the program.

中文题目(简单翻译一下):

将24小时制转换为12小时制的程序。例如,它应该将14:25转换为2:25 PM。输入是两个整数。应该至少有三个函数,一个用于输入,一个用于转换,一个用于输出。将AM/PM信息记录为char类型的值,’ A '表示AM, ’ P '表示PM。因此,用于进行转换的函数将具有一个char类型的按引用调用形参,以记录它是AM还是PM。(该函数还有其他参数。)包含一个循环,让用户对新的输入值一次又一次地重复这个计算,直到用户说他想结束程序。

代码:

#include <iostream>

using namespace std;
int time_24_hour,time_24_minute,time_12_hour,time_12_minute;

void Input(){
    cout<<"请输入时间(24小时制,小时和分钟之间用空格区分):"<<endl;
    cin>>time_24_hour;
    cin>>time_24_minute;
    if(time_24_minute<0||time_24_hour<0||time_24_hour>24||time_24_minute>60){
        cout<<"输入错误程序退出!"<<endl;
        exit(0);
    }
}

void Output(){
    char time_quanyum;
    if(time_24_hour>=12){
        time_quanyum='P';
    }
    else{
        time_quanyum='A';
    }
    if(time_12_minute<10){
        cout<<"转换成12小时制之后的时间为 "<<time_12_hour<<":0"<<time_12_minute<<" "<<time_quanyum<<endl;
    }
    else{
        cout<<"转换成12小时制之后的时间为 "<<time_12_hour<<":"<<time_12_minute<<" "<<time_quanyum<<endl;
    }
}

void Conversion(){
    if(time_24_hour<=12){
        time_12_hour=time_24_hour;
    }
    else{
        time_12_hour=time_24_hour-12;
    }
    time_12_minute=time_24_minute;
}


int main() {
    char choice;
    do{
        Input();
        Conversion();
        Output();
        cout<<"是否继续转换?(y或n)"<<endl;
        cin>>choice;
        if(choice!='y'&&choice!='n'){
            cout<<"输入错误程序退出!"<<endl;
            exit(0);
        }
    }while(choice=='y');
    cout<<"退出成功!"<<endl;
    return 0;
}

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值