c - 多次输入变量answer会退出整个程序

标签 c

上下文:我正在尝试为我的类(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/

相关文章:

c - 使用pthread在C中生成随机数的最正确方法是什么

php - 在扩展中向 $_SERVER 添加条目

c - fgets 工作然后返回访问冲突

c - 删除通过引用传递给函数的链表中的节点

c - 如何将 const uint8_t * const 转换为 bool

c - C 中带有指针的结构体的简单求和

c - 如何使用 fscanf 将大量输入从文件中提取到结构中。美标 C89(90)

c - 返回主菜单时出现问题 - C 编程

c - OpenMP 和共享结构和指针

c# - 在 C# 上用 union 声明 C 结构