【问题标题】:This `do..while` loop isn't working这个 `do..while` 循环不起作用
【发布时间】:2011-05-01 19:41:32
【问题描述】:
int sc1,sc2,a=0,b=0;

do
{

 printf("Give the scores\n");

 scanf("%d %d", &sc1,&sc2);

 //===============================================

 if (sc1 > sc2)     
   a+=1;
 else if (sc1<sc2)
   b+=1;
 else if (sc1==sc2)
   printf("tie\n");

 //===============================================

 if (a>b)    
    printf("team 1 is in the lead\n");
 else if (a<b)
    printf("team 2 is in the lead\n");
 else if (b==a)
    printf("tie\n");      

}
while((a==3) || (b==3));

//===============================================


if (a==3)
  printf("team 1 got the cup");
else
  printf("team 2 got the cup");

我觉得我写错了。我已经搜索了很多,但似乎找不到它有什么问题。

(两支球队中的一支可以赢得杯赛,该球队必须获得3胜)

*否则如果(sc1

*else if(a>b)

【问题讨论】:

  • 如果您准确描述出了什么问题会有所帮助。
  • 为什么不用 cin 和 cout 而不是 scanf 和 printf?

标签: c++ loops while-loop do-while


【解决方案1】:
while((a==3) || (b==3));

仅当ab 为三时才会循环。如果您想等到其中之一是三个,请使用:

while ((a!=3) && (b!=3));

【讨论】:

    【解决方案2】:

    您的循环条件不正确。提前停止是因为两支球队都没有得分 3。循环直到其中一方得分达到 3:

    while((a < 3) && (b < 3));
    

    【讨论】:

      【解决方案3】:

      基本上,您是在告诉它在 a 或 b 仍等于 3 时循环。这不是您想要的。你要while((a&lt;3) &amp;&amp; (b&lt;3))

      【讨论】:

        【解决方案4】:

        如果我正确阅读了您的问题,您希望终止条件是“a”或“b”团队之一的得分为 3。但是,在您的代码中,您已经编写了唯一的while 循环的方式是如果其中一个团队的得分为 3。你想要:

        while( !( a==3 || b == 3) )
        

        【讨论】:

        • @Seth Carnegie not 是 gcc 扩展,! 是正确的。很好的收获。
        • 哦,对不起,我不使用 g++,所以我永远不会喜欢not。对此感到抱歉。
        • not! 的别名,而不是扩展名。
        【解决方案5】:

        你的条件:

        while((a==3) || (b==3));
        

        表示只要ab 等于3,循环就会继续。您确定这是您想要的吗?

        【讨论】:

        • 是的,我想输入分数,直到两支球队中的一支(team1 或 team20 达到 3(获胜)。
        • @Nikos Angelis Junior - 我建议你检查你的代码。如果 team1 赢了 4 次会怎样?
        • 达不到4,do..while会终止(增量固定为1)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        • 2023-02-11
        • 2013-05-06
        • 1970-01-01
        相关资源
        最近更新 更多