#include <stdio.h>
#include <string.h>
main()
{
int h, m;
char designator[] = "";
printf("Please enter the hours: ");
scanf("%d", &h);
if (h < 0 || h > 23)
{
printf("Please enter a proper time!");
}
else
{
printf("Please enter the minutes: ");
scanf("%d", &m);
if (m > 59 || m < 0)
{
printf("Please enter a proper time!");
}
else if (h == 0 && m == 0)
{
strcpy(designator, "midnight");
}
else if (h == 12 && m == 0)
{
strcpy(designator, "noon");
}
else if (h == 0)
{
strcpy(designator, "am");
h = h + 12;
}
else if (h < 12)
{
strcpy(designator, "am");
}
else if (h > 12)
{
strcpy(designator, "pm");
h = h - 12;
}
printf("The time is: %d:%d %s", h, m, designator);
}
}
你好!当我运行这段代码时,我得到一个非常意外的输出。变量(特别是m)不应该改变。它们被用作scanf()的输入,但我无意改变它们。我假设变量有问题或者与IF的,但我真的不知道是什么问题,我的代码:/变量的内容意外改变?
这是出现在命令行:
请输入时间: 23
请输入分钟:15
的时间是:11:109时
我试图找出其中“109”是来自,但我不知道任何责任。我对C很陌生,所以可能有些东西对我来说还不清楚,但我很乐意去了解它们。
是否有任何理由为什么指定变量影响其他变量?还是仅仅是你在那里提到的未定义的行为? – NugNugs
@NugNugs基本原因是所有的局部变量都存储在CPU核心堆栈中,并占用编译器决定的足够空间。这意味着当你写出数组的界限时,你可能会覆盖存储其他变量的栈的内存。 –