当我 运行 程序时,最后一个 "if" 语句不起作用

The last "if" statement is not working when I run the program

每次我 运行 程序时,最后的 "if" 语句不起作用,这意味着如果我输入 "no",循环不会中断。有人可以帮我吗?

#include <stdio.h>

int main() {
  int age, i;
  char ans;

  for (i = 0; i < 3; i++) {
    printf("\n enter your age:");
    scanf("%d", &age);

    if (age > 18) {
      printf("your age is %d, you are allowed to enter", age);
    } else if (age == 18) {
      printf("I don't know what to do with you");
    } else {
      printf("your age is %d, you are not allowed to go in", age);
    }

    printf("\n continue?");
    scanf(" %c", &ans);

    if (ans == 'no') {  // <-- here
      break;
    } else {
      continue;
    }
  }

  return 0;
}

使用if (ans == 'n')。如果要使用单词"no",则必须将变量ans的类型更改为char数组,并使用strcmp()方法比较字符串。

您使用了 %c,这是针对字符的。 相反,使用 %s.

在c编程中,单引号(即'c')用于字符,双引号(即"c")用于字符串。双引号中的最后一个字符为 NULL。

注意:我们不能像'no'.

那样在单引号中保留两个字符

在你的情况下,首先,将 ans 声明为字符数组(即字符串)。

char ans[SIZE_AS_PER_REQUIREMENT];

To take input在这,

scanf("%s",ans);

为了获得更好的用户体验,请在输入之前向用户提供适当的消息。

printf("\n Do you want to continue(yes/no)?");

现在将用户的答案与程序的条件进行比较,我们有 C 语言字符串库(即 string.h),在使用任何 C 语言内置字符串函数之前包含它。

#include <string.h>

并根据要求使用任何字符串函数 strcmp or stricmp。这里我将使用 stricmp,因为用户可能会输入 "no"/"No"/"NO"。 stricmp 忽略大小写。

stricmp(string1,string2)

它returns

  • 负数,如果 string1 小于 string2
  • 如果 string1 等于 string2 则为零
  • 如果 string1 大于 string2,则为正数

因此,对于我们的案例,我们检查零。

看下面的程序,我只是在你的代码中添加了这些。

#include <stdio.h>
#include <string.h>
int main() {
  int age, i;
  char ans[5];//declare ans as character array

  for (i = 0; i < 3; i++) {
    printf("\n enter your age:");
    scanf("%d", &age);

    if (age > 18) {
      printf("your age is %d, you are allowed to enter", age);
    } else if (age == 18) {
      printf("I don't know what to do with you");
    } else {
      printf("your age is %d, you are not allowed to go in", age);
    }

    printf("\n Do you want to continue(yes/no)?");
    scanf("%s",ans);//take input as string in ans, its character array

    if (stricmp(ans,"no") == 0) {  // 0 means both are equal
      break;
    } else {
      continue;
    }
  }

  return 0;
}