C#代码只给出了一步,通过预期的效果? [英] C# code only gives expected results on step through?

查看:227
本文介绍了C#代码只给出了一步,通过预期的效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我有一个骰子掷应用...



当我通过它通常函数的代码步骤和'结果'包含扔结果的正确数量和他们似乎是随机的,当我离开的代码运行,做的正是它产生一组相同的数字是一样的。



我敢肯定,这是一个逻辑错误我看不到,但它摆弄了几个小时处理不当情况好转,所以任何帮助大大appriciated。 :)

 类骰子
{

公众诠释[]卷轴(INT _throws, INT _sides,诠释_count)
{
随机RND =新的随机();
INT [] =结果新INT [_throws]
//每一套骰子扔通数据计算方法
的for(int i = 0; I< _throws;我++)
{
INT thisThrow =计算( _sides,_count);
//添加每个掷到数组的新指数...重复每一个扔
结果[I] = thisThrow;
}

返回结果;
}


私人诠释计算(INT _sides,诠释_count)
{
随机RND =新的随机();
INT []结果=新的INT [_count]
INT总= 0;
//每个骰子扔放入数据结果
的for(int i = 0; I< _count;我++)
{
结果[I] = rnd.Next (1,_sides);
}
//计数结果
的值(INT X = 0; X< _count; X ++)
{
总=总+结果[X ];
}
//返回总所有骰子对卷方法
总回报;
}
}


解决方案

第一错误:不要使用随机的多个实例,用一个实例,并通过与其他参数一起


Ok so I have a dice throw app...

When I step through the code it functions normally and 'results' contains the correct number of throw results and they appear to be random, when I leave the code to run and do exactly the same thing it produces a set of identical numbers.

I'm sure this is a logical error I cannot see but fiddling with it for hours hasnt improved the situation, so any help is much appriciated. :)

    class Dice
{

    public int[] Roll(int _throws, int _sides, int _count)
    {
        Random rnd = new Random();
        int[] results = new int[_throws];
        // for each set of dice to throw pass data to calculate method
        for (int i = 0; i < _throws; i++)
        {
            int thisThrow = Calculate(_sides, _count);
            //add each throw to a new index of array... repeat for every throw
            results[i] = thisThrow; 
        }

        return results;
    }


    private int Calculate(int _sides, int _count)
    {
        Random rnd = new Random();
        int[] result = new int[_count];
        int total = 0;
        //for each dice to throw put data into result
        for (int i = 0; i < _count; i++)
        {
            result[i] = rnd.Next(1, _sides);
        }
        //count the values in result
        for (int x = 0; x < _count; x++)
        {
            total = total + result[x];
        }
        //return total of all dice to Roll method
        return total;
    }
}

解决方案

First mistake: Never use multiple instances of Random, use a single instance, and pass that along with the other parameters.

这篇关于C#代码只给出了一步,通过预期的效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆