1

我想将 24 小时时间转换为 12 小时时间。

int midHour = 15;
int midHour12 = midHour - 12;
if(midHour <= 12)
{
    midHour12 = midHour;
    string meridiem("AM");
}
else
{
    midHour12 = midHour - 12;
    string meridiem("PM");
}
cout << midHour12 << meridiem;

但是,我不知道如何让 meridiem 从 if else 块中“逃脱”。它的范围太小了。如何在 if-else 块之外访问 meridiem 的值?

if 语句块中变量初始化的答案不能回答这个问题。

4

4 回答 4

3

You need to declare meridiem outside the if block. You also need to use = to assign to meridiem after it's declared:

string meridiem;                                                               /*
^^^^^^^^^^^^^^^^                                                               */

if (midHour <= 12)
{
    midHour12 = midHour;
    meridiem = "AM";                                                           /*
    ^^^^^^^^^^^^^^^^                                                           */
}
else
{
    midHour12 -= 12;
    meridiem = "PM";                                                           /*
    ^^^^^^^^^^^^^^^^                                                           */
}

Otherwise the variable will go out of scope by the ending bracket.

于 2013-06-13T17:18:09.640 回答
2

You should declare meridiem first:

   int midHour12;
    string meridiem;
    if(midHour <= 12)
    {
        midHour12 = midHour;
        meridiem = "AM";
    }
    else
    {
        midHour12 = midHour - 12;
        meridiem = "PM";
    }
    cout << meridiem;

Or if You don't need meridiem later, just print midHour12, and in the if-else print "AM" or "PM"

于 2013-06-13T17:18:11.827 回答
2

您必须meridiem在 if-else 块之前声明,因为在{...}内声明的变量只能从块内看到。

string meridiem;

int midHour = 15;
int midHour12 = midHour - 12;
if(midHour <= 12)
{
    midHour12 = midHour;
    meridiem = "AM";
}
else
{
    midHour12 = midHour - 12;
    meridiem = "PM";
}
cout << midHour12 << meridiem;
于 2013-06-13T17:20:04.167 回答
2

c++11 lambda 答案只是为了好玩:

#include <string>

 auto currentTime = [](int midHour)
 {
    return (midHour <= 12) ? std::to_string(midHour) + "AM" : std::to_string(midHour - 12) + "PM";
 }

 cout << currentTime(15);
于 2013-06-13T17:37:51.667 回答