【问题标题】:Coin is thrown until one side falls three times in a row投掷硬币,直到一侧连续下降 3 次
【发布时间】:2018-05-22 06:42:37
【问题描述】:

我是编程新手,但对一项任务有疑问:

投掷硬币,直到一侧连续掉落 3 次

int throwing = 0;

int tail=0;
int head=0;
int counter= 0;
Random rnd = new Random();

do
{
    throwing = rnd.Next(1, 3);
    Console.WriteLine(bacanje);
    counter++;

    if (throwing == 1)
    {
        tail++;
    }
    else if (throwing == 2)
    {
        head++;
    }

} while (tail != 3 && head!= 3);

所以我的问题是它不想连续 3 次,当结果如下时程序退出:头,头,尾,头。它应该是:头,头,头。

不确定代码中要更改什么,如果有人有任何建议,我将不胜感激。谢谢

【问题讨论】:

  • 作为旁注,虽然你所做的是正确的,但通常在 c# 中你“接受”第一个数字是 0 并且你接受它......rnd.Next(2) 然后if (throwing == 0) {} else {}(不需要第二个ifelse 就足够了...正如拉丁人所说的tertium non datur,没有第三个可能的结果)

标签: c# c#-2.0


【解决方案1】:

如果 throw 发生变化,您永远不会为另一个重置计数器,您只需将另一个重置为 0

if (throwing == 1)
{
    tail++;
    head = 0;
}
else if (throwing == 2)
{
    head++;
    tail = 0;
}

【讨论】:

  • while((tail + head) != 3); 不太喜欢这种微优化,它不会使代码更清晰,而且可能不会加快速度起来。
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多