C语言程序中scanf与printf执行顺序异常的问题排查及修复咨询
Hey there, let's sort out why your input/output sequence is behaving unexpectedly and get it working as intended!
The Root Cause
The main problem is the extra newline characters (\n\n) in your first scanf format string. When you include \n in a scanf specifier, it tells the function to keep eating all whitespace (newlines, spaces, tabs) until it encounters a non-whitespace character. That's why your program was making you input twice before showing the printf output—those \n\n were forcing scanf to wait for more input after your first entry.
On top of that, your random number generation was out of order: you called rand() before initializing the seed with srand(), which means you'd get the same "random" number every time you ran the program.
Fixed Code
Here's the adjusted code that follows your desired scanf → printf → scanf order and fixes the random number issue:
#include <stdio.h> #include <stdlib.h> #include <time.h> int d; int s; int main() { // r for rand, d for dividing number, s for sum int r; // Initialize random seed FIRST (critical for true randomness) time_t SFE = time(NULL); srand(SFE); // Generate random number (0-9 here; change to %10 +1 for 1-10 if needed) r = rand() % 10; printf("Please choose a number: "); scanf("%d", &d); // Removed the problematic \n\n printf("\nYour result is: %d. \nWhat is the random number?:", r * d); scanf("%d", &s); if (s == r) { printf("\nYou have the correct number!"); } else { printf("\nSorry, that's wrong. The correct answer is %d! Try again next time!", r); } return 0; }
Key Fixes Explained
- Removed
\n\nfromscanf:scanf("%d")automatically skips leading whitespace, so you don't need to add newlines in the format string. This lets the first input complete immediately, so theprintfruns right after, then the secondscanfwaits for your next input—exactly the flow you wanted. - Reordered random number setup: Calling
srand(time(NULL))before anyrand()calls ensures your random number changes every time you run the program. Previously, you were generating a number before initializing the seed, which would give the same value on every launch.
内容的提问来源于stack exchange,提问作者Its-Ayd On Us

