您好考慮下面的簡單的程序:炭未按預期運行在C
int main(void)
{
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
}
輸出爲:
please enter a number
2
the number multiple by 3 is 6.000
enter a word with four char
ffff
the chars in reverse order are
fff
3字符打印到控制檯,如果我移動鍛鍊的碼塊2以上1:
int main(void)
{
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
}
結果如預期:
enter a word with four char
ffff
the chars in reverse order are
ffff
please enter a number
2
the number multiple by 3 is 6.000
我想知道爲什麼它在工作,當我更改代碼塊的順序時,我該如何解決它,謝謝。
極爲常見的常見問題。輸入緩衝區中留有新的行字符。例如查看鏈接副本,「當* scanf()無法按預期工作時」部分。 – Lundin