【问题标题】:do while keeps repeating even when entered the correct value C即使输入了正确的值,do while 也会不断重复 C
【发布时间】:2020-08-28 21:15:23
【问题描述】:

我想开始一个 Y 和 N Q&A 的程序。

#include <stdio.h> 
#include <stdlib.h>

int main(){
    char answer[256];
    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%s", answer);
    printf("%s", answer);
    }while(answer != "Y" || answer != "N")
;
    return 0;
}

如您所见,我声明了一个 char 类型的 256 个元素的变量,然后使用 scanf 我记录了用户输入并将其存储在答案中。然后,只要用户输入大写的 Y 或 N,循环就会一直询问。问题是,使用此实现,即使我输入 Y 或 N,程序也会不断询问。我应该将 char 声明更改为单个字符吗?我已经试过了:

#include <stdio.h> 
#include <stdlib.h>

int main(){
    char answer;
    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%c", answer);
    printf("%c", answer);
    }while(answer != 'Y' || answer != 'N')
;
    return 0;
}

但我收到了警告:

warning: format '%c' expects argument of type 'char *', but argument 2 has type int' [-Wformat=]
scanf("%c", answer);

有人对这个问题有澄清吗?

【问题讨论】:

  • answer != "Y" 始终为真。 answer的地址不等于"Y"的地址。
  • 您无法将字符串与==!= 进行比较。要么使用女巫字符,要么使用字符串比较函数。
  • @EugeneSh.,它们不是字符串......它们是字符
  • @JoelFan 在第一个 sn-p 中它们是字符串
  • answer != 'Y' || answer != 'N' 在第二个代码中也始终为真。

标签: c do-while negation logical-or logical-and


【解决方案1】:

此声明

然后,只要用户输入一个 大写 Y 或 N。

意味着当用户输入“Y”或“N”时循环将停止迭代,不是吗?

这个条件可以写成这样

strcmp( answer, "Y" ) == 0 || strcmp( answer, "N" ) == 0  

所以这个条件的否定(当循环将继续它的迭代时)看起来像

!( strcmp( answer, "Y" ) == 0 || strcmp( answer, "N" ) == 0 )

相当于

strcmp( answer, "Y" ) != 0 && strcmp( answer, "N" ) != 0  

请注意,您必须比较字符串(使用 C 字符串函数 strcmp)而不是指向它们的第一个字符的指针,这些字符总是不相等的。

所以第一个程序的do-while循环中的条件应该是

    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%s", answer);
    printf("%s", answer);
    }while( strcmp( answer, "Y" ) != 0 && strcmp( answer, "N" ) != 0 )
;

那就是应该使用逻辑与运算符。

在第二个程序中,您必须像这样使用 scanf 调用

scanf( " %c", &answer);
       ^^^^   ^

和同样的逻辑AND运算符

    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf(" %c", &answer);
    printf("%c", answer);
    }while(answer != 'Y' && answer != 'N')
;

【讨论】:

  • 感谢您分享您的答案。不过,有些东西我仍然无法掌握。在 while 之后的条件中,我放置了逻辑 OR 运算符,因为如果答案是“Y”或“N”,那么程序将停止。我不明白为什么要使用逻辑 AND,因为在提示答案时我不会同时满足这两个条件。
  • @almrog "or" 对于停止循环的原因是有意义的。但是... while() 正在寻找继续循环的理由。所以答案不能是 Y,答案不能是 N。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2018-01-18
相关资源
最近更新 更多