1

我有个问题。当我尝试要求用户输入 yes 或 no 作为单个字符并使用括号设置 char 变量时,因为我得到 Y 或 y 在我的 if 语句中无效。如果我不带括号这样做,我只会得到将在 if 语句中评估的 ascii 值。以下代码将无法评估 recAnswer 值。当我在 printf 中输出值时,它会根据输入显示 recAnswer = "Y" 或 "y"。我试过 if(&recAnswer == "Y") 和 if(*recAnswer = "Y")

int main(int argc, char** argv)
{
  int numEntered;
  char recAnswer[1];

  while(numEntered < 1 || numEntered > 15) // Continually ask user to enter a number until the number entered is between 1 and 15 . 
  {
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } 
  printf("\nDo you want to get the factorial value recursively? Enter Y or N:"); //Ask user if they want to get the answer recursively 
  scanf(" %c",&recAnswer);
     
if(recAnswer == "y" || recAnswer == "Y")
{
  printf("The recursive value of %d is %d", numEntered, recursive(numEntered)); //Print out recursive value
}   
else
{
  printf("The non-recursive value of %d is %d", numEntered, nonRecursive(numEntered));  //Print out looped value
}
return 0;
}

感谢您对此进行调查

4

1 回答 1

2

对于初学者这个循环

  while(numEntered < 1 || numEntered > 15) // Continually ask user to enter a number until the number entered is between 1 and 15 . 
  {
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } 

调用未定义的行为,因为变量numEntered未初始化。

int numEntered;

将 while 循环替换为 do-while 循环,例如

  do
  {
     numEntered = 0;
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } while(numEntered < 1 || numEntered > 15); // Continually ask user to enter a number until the number entered is between 1 and 15 . 

其次,如果您要输入一个字符,那么声明一个包含一个元素的数组是没有意义的

char recAnswer[1];

(注意:此外,您使用的转换说明符 %c 的参数不正确

scanf(" %c",&recAnswer);
            ^^^^^^^^^^^ 
  • 尾注)

声明一个类型的对象char 并初始化它,例如用常量'n'。

char recAnswer = 'n';

并通过以下方式更改 if 语句

if(recAnswer == 'y' || recAnswer == 'Y)

那就是使用字符整数常量而不是字符串文字。

于 2021-04-02T19:37:23.627 回答