【问题标题】:Number guessing game always returns the same output猜数字游戏总是返回相同的输出
【发布时间】:2021-07-01 01:04:42
【问题描述】:

我正在使用 if...else 语句制作一个从 1 到 10 的简单数字猜谜游戏,它第一次成功,但似乎总是输出“你没有猜对”。当我猜测或相反时。对一些帮助会很有帮助,所以这是我在提出这个问题时提出的解决方案:

//This is the first solution I've come up with.
#include <stdio.h>
#include <stdbool.h>

int main() {
  int guessingNumber = '5';
  printf("Guess from 1-10: ");
  scanf("%d", &guessingNumber);

  if (guessingNumber == true) {
    printf("You guessed it!\n");
  }
  else {
    printf("You didn't guess it correctly.\n");
  }
  return 0;
}


//Here is the second one.
#include <stdio.h>

int main() {
  int guessingNumber = '5';
  int guess;
  printf("Guess from 1-10: ");
  scanf("%d", &guess);

  if (guessingNumber == guess) {
    printf("You guessed it!\n");
  }
  else {
    printf("You didn't guess it correctly.\n");
  }
  return 0;
}

我确定导致此问题的问题出在第一个解决方案的以下几行中:

printf("Guess from 1-10: ");
      scanf("%d", &guessingNumber);
    
      if (guessingNumber == true) {
        printf("You guessed it!\n");

这来自第二个解决方案,我确信问题(也可能)来了:

printf("Guess from 1-10: ");
  scanf("%d", &guess);

  if (guessingNumber == guess) {
    printf("You guessed it!\n");

【问题讨论】:

  • int guessingNumber = '5'; 您在这里使用的是char。应该是int guessingNumber = 5;
  • 如果您删除 ''s,请立即澄清第二个工作。这些用于表示“给我这个字符的整数(例如 ascii)值”,而不是数值 5。
  • @JohnnyMopp 感谢您的快速回答!我确实认为我之前这样做过,但现在有效。我想我只是糊涂了,再次感谢您!
  • @yhrycanus 哦,这就是它的作用,我只是很困惑,所以我不知道该怎么做。不过感谢您提供的信息!

标签: c if-statement


【解决方案1】:

比较是不安全的 int 和 bool。检查以下内容。

int main()
{
    int actualNumber, guessingNumber = 5;
    printf("Guess from 1-10: ");
    scanf_s("%d", &actualNumber);

    if (guessingNumber == actualNumber) {
        printf("You guessed it!\n");
    }
    else {
        printf("You didn't guess it correctly.\n");
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多