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
答案 0 :(得分:2)
如果用户输入的文字类似于&#39;一个&#39; !会发生什么? 始终检查错误:
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;
}
答案 1 :(得分:0)
如果您询问这两行之间是否有新的空行,您只需在第一个printf语句后添加printf("\n");
即可。
如果你想把空格放在任何地方,请使用printf(" ");
这将增加空间。
使用int和while循环打印所需数量的空格或新空行。
示例:
int main()
{
int i;
i = 0;
while (i < 30)
{
printf(" ");
i++;
}
printf("X\n");
return 0;
}