【问题标题】:How to ask question continuously until it meets requirements of having to meet a condition in c [closed]如何不断提出问题,直到它满足必须满足c中的条件的要求[关闭]
【发布时间】:2021-11-16 13:03:21
【问题描述】:

我正在使用 cs50 在线 IDE,所以我也在顶部使用 cs50 库。我试图让它继续问“你还好吗?”这个问题。直到你说“y”或“n”(大写或小写)。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
 
    char answer;
    do
    {
        char answer = get_char("are you okay Y/N ");
        if (answer == 'y' || answer == 'Y')
        {
            printf("you are okay");
        }
            else if (answer == 'n' || answer == 'N')
        {
            printf("you are not okay ");
        }

    }
   
    while(answer != 'y' || answer != 'Y' || answer != 'n' || answer != 'N');
    
}

【问题讨论】:

  • while 条件下将|| 更改为&amp;&amp;
  • 如果你了解De Morgan's laws(我真的建议你应该这样做),那么你就会知道answer == 'y' || answer == 'Y'的反面是not answer != 'y' || answer != 'Y'。跨度>
  • 请使用标点和大写,而不是无意义的粗体格式。您寻求帮助的人会认为这是礼貌,并认为您在寻求帮助方面付出了努力。
  • @Fkhadim123 你已经得到了关于你需要在第一条评论中改变什么以及提到德摩根定律背后的原因的确切答案。

标签: c if-statement conditional-statements cs50


【解决方案1】:

在 C 语言中学习布尔逻辑时,常识会让你走得很远。那就是:养成大声/在脑海中说出你写下的台词的习惯:

while(answer != 'y' || answer != 'Y' || answer != 'n' || answer != 'N');

翻译成英文:

“而答案不是y或者不是Y或者不是……”

在这里你应该闻到鱼的味道。正确的英语/逻辑宁愿是:

“虽然答案不是y 并且它不是Y 并且...”

抛开常识不谈,De Morgan's Laws 是学习任何编程之前的必备知识。

【讨论】:

  • 程序还没有编译
  • 实际上是因为我两次声明了“答案”,它现在可以编译并按预期工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2022-12-18
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 2020-08-29
相关资源
最近更新 更多