【问题标题】:Inputting the variable answer more than once exits the whole program多次输入变量 answer 会退出整个程序
【发布时间】:2019-10-03 05:21:01
【问题描述】:

上下文:我正在尝试为我的班级制作一个猜数程序。该程序应该生成从 1 到 100 的随机数,如果它太小,我按 '>' 得到一个较小的数字,或者我可以按 '我的问题是,如果我在 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

【问题讨论】:

  • 由于您将空终止字符串读入单个char,您将有未定义的行为
  • 使用 -Wall -Wextra 编译并倾向于警告
  • 虽然这无关紧要,但您可能希望将随机数生成逻辑放在一个循环中。
  • 与您的问题无关,但为什么是`+ 1 - 1`?编译器很可能会将其优化掉。
  • 如果你想重复动作,你需要一个循环,但你没有它。在输入错误的情况下退出程序对我来说有点苛刻。为什么不只是警告(你已经做了什么)并忽略它?

标签: c


【解决方案1】:

您的代码中需要一个循环,在这里它只是执行然后离开。

类似:

int done = 0;

while (done != 1) {
     scanf(...)

     if (smth) 
         do smth
     else if (smth_else)
         do smth
     [...]
     else if (char == '=')
         done = 1;

}
return 0

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多