上下文:我正在尝试为我的类(class)制作一个猜数字程序。该程序应该生成 1 - 100 之间的随机数,如果它太小,我按“>”以获得较小的数字,或者我可以按“<”以获得更大的随机数,等等。 My问题是,如果我在 scanf 中多次输入“<”、“>”或它们的组合,我的程序就会退出,而不是找到另一个更低/更高的数字。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(void)
{
int randomGen, num;
char answer;
printf("Choose a number between 1 and 100, I will try to guess the number correctly.\n");
printf("If the number is too low, press >. If the number is too high, press <.\n");
printf("If the guess is correct, press =.\n\n");
srand(time(0));
randomGen = rand()%(100 + 1 - 1) + 1;
num = randomGen;
printf("%d\n", num);
scanf("%s", &answer);
if (answer == '>')
{
randomGen = rand()%(num + 1 - 1) + 1;
printf("%d\n", randomGen);
scanf("%s", &answer);
}
else if (answer == '<')
{
randomGen = rand()%(100 + 1 - num) + num;
printf("%d\n", randomGen);
scanf("%s", &answer);
}
else if (answer == '=')
{
printf("Thank you for using my program.\n");
exit(0);
}
else
{
printf("Please use the correct sign, Exiting Program.\n");
exit(0);
}
}
预期结果示例:
48 > 30 > (部分数字低于30)
该计划中会发生什么: !code
最佳答案
您的代码中需要一个循环,这里它只是执行然后离开。
类似于:
int done = 0;
while (done != 1) {
scanf(...)
if (smth)
do smth
else if (smth_else)
do smth
[...]
else if (char == '=')
done = 1;
}
return 0
关于c - 多次输入变量answer会退出整个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212742/