【问题标题】:Is it possible to have an nested conditional statement? [duplicate]是否可以嵌套条件语句? [复制]
【发布时间】:2016-08-19 17:07:29
【问题描述】:

我正在尝试 do-while 条件,其中还有一个 while,我在“你想继续吗?”中遇到问题,它正在跳过它。我的代码有什么问题吗?

do {
    printf("\nEnter the start value:");
    scanf("%d", &start_value);
    printf("\nEnter the end value:");
    scanf("%d", &end value);
    printf("\nEnter the interval value:");
    scanf("%d", &interval_value);
    while (start_value <= end_value) {
        printf("%d ", start_value);
        start_value = start_value + interval_value;
    }
    printf("\nDo you want to continue?");
    scanf("%c", &answer);
} while (answer != 'N' || answer != 'n');

【问题讨论】:

  • scanf("%c", &amp;answer); --> scanf(" %c", &amp;answer);
  • 嗯?您正在为变量“first”和“second”赋值,然后不再使用它们。
  • 好的,Weather Vane 的回答也添加了一个非常有效的观点,但是“跳过”部分是骗人的。如果有人不同意简历,请告诉我。
  • start_valueend_value 应该是 firstsecond,反之亦然。
  • @SouravGhosh:这个副本质量很差。我敢肯定还有更好的。

标签: c do-while


【解决方案1】:

你的条件语句

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

总是true。我建议

while(answer != 'N' && answer != 'n');

(除了上面来自@SouravGhosh 的第一条评论,它清除了输入缓冲区中留下的newline

【讨论】:

  • 我也建议if (scanf(" %c", &amp;answer) != 1) break;
  • 我的主要问题是,我的“你想继续吗?”已被跳过,有什么建议是我的错误吗?
  • @Holow 解决方案位于顶部的第一条评论中,我在回答中提到了这一点。如果不清楚,this answer 也建议这样做。另外,请仔细阅读 scanf 函数的手册页。
猜你喜欢
  • 2013-08-04
  • 2017-04-04
  • 2023-01-28
  • 2014-05-16
  • 2015-07-14
  • 2013-12-22
  • 1970-01-01
  • 2019-12-12
  • 2011-08-12
相关资源
最近更新 更多