写一个程序(sy10_3.cpp),将24小时格式的时间转换成12小时格式。下面是一个示范的对话: Enter time in 24-hour notation : 13:07 That is the same as: 1:07 PM Do you want to try a new case?(y/n) Y Enter time in 24-hour notation : 10:15 That is the same as: 10:15 AM Do you want to try a new case?(y/n) Y Enter time in 24-hour notation : 10:65 There is no such a time as 10:65 Enter another time : Enter time in 24-hour notation : 16:05 That is the same as: 16:05 PM Do you want to try a new case?(y/n) N End of program.
时间: 2024-02-25 17:53:36 浏览: 79
PECL TO TTL
5星 · 资源好评率100%
好的,以下是C++的代码实现:
```c++
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char choice = 'y';
while (choice == 'y' || choice == 'Y') {
int hour, minute;
cout << "Enter time in 24-hour notation : ";
cin >> hour;
if (cin.get() != ':' || !(cin >> minute) || hour < 0 || hour >= 24 || minute < 0 || minute >= 60) {
cin.clear();
cin.ignore(1000, '\n');
cout << "There is no such a time as " << hour << ":" << minute << endl;
cout << "Enter another time : ";
cin >> hour;
cin.get();
cin >> minute;
}
cout << "That is the same as: ";
if (hour == 0) {
cout << "12:";
} else if (hour <= 12) {
cout << hour << ":";
} else {
cout << hour - 12 << ":";
}
cout << setfill('0') << setw(2) << minute << " ";
if (hour < 12) {
cout << "AM";
} else {
cout << "PM";
}
cout << endl;
cout << "Do you want to try a new case? (y/n) ";
cin >> choice;
}
cout << "End of program." << endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个字符变量`choice`,用于控制程序的运行。在`while`循环中,如果用户输入了`y`或`Y`,则继续执行程序。
接着,我们通过`cin`函数读取用户输入的24小时制的时间,并进行格式检查。如果时间格式不正确,我们会清除`cin`的错误标志,忽略之前输入的内容,并要求用户重新输入时间。
如果时间格式正确,我们就将其转换成12小时制,并打印出来。注意,我们使用了`setfill('0')`和`setw(2)`来保证分钟数的输出格式为两位数。
最后,我们询问用户是否要继续输入新的时间。如果用户输入了`n`或`N`,程序就结束。
阅读全文