0

在下面的代码中,我只想printf在程序末尾使用一个来打印 12 小时时间,但我希望它打印 am 或 pm,具体取决于存储在变量 中的哪个am_pm

我以为我读到我可以将字符存储在 int (或浮点数?)中,但我不确定我是否记得正确。当然,这似乎是非法的,因为我遇到了类型错误。

我还读到我可以使用数组来做到这一点,但我还没有了解数组,我想知道是否有更简单的替代方法来解决这个问题。

我知道另一种方法是简单地使用两个printf's,一个我简单地输入“am”,一个我简单地在字符串末尾输入“pm”,但这对我来说似乎是多余的。

#include <stdio.h>

int main(void) {

int hour, minutes, am_pm;

printf("Enter a 24-hour time:"); scanf("%d:%d", &hour, &minutes);
if (hour > 12) 
    {
    hour = (hour - 12); 
    am_pm = "pm"; // ERROR 
    }
else
    am_pm = "am";  // ERROR

printf("Equivalent 12-hour time: %.2d:%.2d%d", hour, minutes, am_pm);

} // end main 

我怎样才能做类似于我上面尝试做的事情?我知道在 python 中我会简单地做一些事情,比如 print("equivalent time is:" + hour + minutes + am_pm)

4

4 回答 4

3

可以将单个字符存储在 int 中。int 的值是字符的 ASCII 码。每个 int 只有一个字符。这可能是你(错误)记得的。

正如其他人所写,将 am_pm 声明为 a char *,或者更好的是 a const char *。告诉编译器指向的const字符串是只读的。

另一种选择是将 am_pm 中的 'a' 或 'p' 存储为 int,

am_pm = 'p'; // Note single quotes for character (double quotes for strings)

然后写

printf("Equivalent 12-hour time: %.2d:%.2d%cm", hour, minutes, am_pm);

%c means interpret am_pm as a character. This takes advantage of the fact that only the first letter of "am"/"pm" changes.

于 2012-12-18T08:33:18.150 回答
2

您不能将字符串文字存储在 int 中!

声明am_pm为:

char *am_pm;

并使用打印%s

printf("Equivalent 12-hour time: %.2d:%.2d%s", hour, minutes, am_pm);
于 2012-12-18T08:30:43.003 回答
2

First of all am_pm is declared as int and a few lines below you try to assign string to it. This is illegal. The other answers show how to correct this. I'd add another solution:

#include <stdio.h>

int main(void) {

int hour, minutes;
int is_pm = 0;

printf("Enter a 24-hour time:"); scanf("%d:%d", &hour, &minutes);
if (hour > 12) 
{
    hour = (hour - 12); 
    is_pm = 1;
}


printf("Equivalent 12-hour time: %.2d:%.2d%s", hour, minutes, (is_pm)?"PM":"AM");

} // end main 

If this seems strange to you - read about 'question mark operator'.

于 2012-12-18T08:34:45.870 回答
1

使用const char *for am_pm,例如更改:

int hour, minutes, am_pm;

... 

printf("Equivalent 12-hour time: %.2d:%.2d%d", hour, minutes, am_pm);

到:

int hour, minutes;
const char * am_pm;

...

printf("Equivalent 12-hour time: %.2d:%.2d %s", hour, minutes, am_pm);
于 2012-12-18T08:30:43.887 回答