C语言的随机数猜谜游戏。
用户有 10 次猜测,如果没有猜对,游戏将退出。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int theNumber;
int userGuess;
int counter = 10;
int lowerBound = 1, upperBound = 100;
// seed function
srand((unsigned)time(NULL));
// generates number between 1 and 100
theNumber = lowerBound + rand() % (upperBound - lowerBound + 1);
printf("Please guess a number (1-100): ");
for (counter = 9; counter <= 10; counter--) {
// get users guess
scanf("%d", &userGuess);
if (userGuess == theNumber) {
printf("You guessed it! The number was: %d", theNumber);
break;
}
if (userGuess < theNumber && counter >= 1)
printf("Your guess was too low. You have %d guesses remaining. Guess higher: ", counter);
if (userGuess > theNumber && counter >= 1)
printf("Your guess was too high. You have %d guesses remaining. Guess lower: ", counter);
if (counter == 0) {
printf("\nYou ran out of guesses. The number was: %d \n", theNumber);
break;
}
}
return 0;
}
示例输出:
Please guess a number (1-100): 100
Your guess was too high. You have 9 guesses remaining. Guess lower: 90
如何在第一个 printf 语句后添加一个空格,使输出看起来像这样?
期望的输出:
Please guess a number (1-100): 100
Your guess was too high. You have 9 guesses remaining. Guess lower: 90
最佳答案
如果用户输入像“一”这样的文本!会发生什么?
始终检查错误:
if (scanf("%d", &userGuess) != 1){
printf("incorrect input.\n");
return 1;
}
如果您需要垂直空间,请使用 printf("\n");
。
如果您只需要一次垂直空间,请使用:
if (counter == 9)
printf("\n");
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int theNumber;
int userGuess;
int counter = 10;
int lowerBound = 1, upperBound = 100;
// seed function
srand((unsigned)time(NULL));
// generates number between 1 and 100
theNumber = lowerBound + rand() % (upperBound - lowerBound + 1);
printf("Please guess a number (1-100): ");
for (counter = 9; counter <= 10; counter--) {
// get users guess
if (scanf("%d", &userGuess) != 1){
printf("incorrect input.\n");
return 1;
}
//if (counter == 9)
printf("\n");
if (userGuess == theNumber) {
printf("You guessed it! The number was: %d", theNumber);
break;
}
if (userGuess < theNumber && counter >= 1)
printf("Your guess was too low. You have %d guesses remaining. Guess higher: ", counter);
if (userGuess > theNumber && counter >= 1)
printf("Your guess was too high. You have %d guesses remaining. Guess lower: ", counter);
if (counter == 0) {
printf("\nYou ran out of guesses. The number was: %d \n", theNumber);
break;
}
}
return 0;
}
关于c - 如何在第一个 printf 语句后添加一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034553/