#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核心堆棧中,並佔用編譯器決定的足夠空間。這意味着當你寫出數組的界限時,你可能會覆蓋存儲其他變量的棧的內存。 –