首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >for and while循环混淆来自括号的第7教程视频

for and while循环混淆来自括号的第7教程视频
EN

Stack Overflow用户
提问于 2017-07-07 09:35:43
回答 1查看 38关注 0票数 0
代码语言:javascript
复制
using System;

namespace SeventhConsoleProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Random NumGen = new Random ();
            int diceRoll = 0;   // The variable used to roll the dice
            int attempts = 0;   // The amount of times it takes Tom to get a 6
            int amountmodifier = 10;    //To edit the amount of times that the program loops so that I can get a more accurate average

            Console.Write ("Tom wants to roll a dice multiple times and see how long it takes to get a 6.\nTom wants to get the average of " + amountmodifier + " successful attempts ");
            Console.ReadKey ();
            Console.WriteLine ();

            for (int amount = 1; amount <= amountmodifier; amount++) {
                while (diceRoll != 6) {
                    diceRoll = NumGen.Next (1, 7);
                    attempts++;
                }
            }
            int averageafter = attempts / amountmodifier;

            Console.WriteLine ("Over " + amountmodifier + " successful attempts it took Tom an average of " + averageafter + " attempts to get a 6");
            Console.ReadKey ();
        }
    }
}

我最近在c#上观看了Brackey在他的教程系列中的第七个视频。我正在努力完成他在评论中留下的挑战。

最初的任务是创建一个程序,让"Tom“掷骰子,然后他一直掷骰子直到得到6分。然后用户应该被告知"Tom”掷了多少次骰子才得到6分。这部分我想出来了。

然而,挑战部分是你必须弄清楚如何找到"Tom“滚动6的10次成功尝试的平均值。这部分让我困惑。我的代码背后的逻辑是for循环将重复10次,或者是我将变量amountmodifier更改为多少次。每次for循环通过它的循环时,它都会经历while循环,该循环将继续,直到"Tom“滚动6,一旦"Tom”滚动6,while循环将退出,for循环将再次运行,重复10次。

我的想法是,在for循环完成后,“尝试”的数量将具有10次成功尝试的信息,并将其除以amountmodifier,以创建这些尝试的平均值。然而,它不会工作。从我可以得出的结论,要么是for循环没有重复10次,要么是attempts数量在不断地重置。我不明白为什么。如果有人愿意解释的话,我会非常感激的。

EN

回答 1

Stack Overflow用户

发布于 2017-07-07 09:41:49

问题出在这里:

代码语言:javascript
复制
for (int amount = 1; amount <= amountmodifier; amount++) {
    // Add this line:
    diceRoll = 0;

    while (diceRoll != 6) {
        diceRoll = NumGen.Next (1, 7);
        attempts++;
    }
}

问题是,在滚动6之后,diceRoll的值是6。因此,下一次通过for循环时,根本不会进入while循环,因为diceRoll已经是6了。

修复方法是添加我建议的行,以确保diceRoll重置为0(与最初一样)。

更好的是,因为您不需要在其他地方使用diceRoll,所以只需在此处声明它:

代码语言:javascript
复制
for (int amount = 1; amount <= amountmodifier; amount++) {
    int diceRoll = 0; // and get rid of the similar line at the top of Main
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44961250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档