简体   繁体   English

C#中随机交替正负数数组

[英]Array Of Random Alternate Positive And Negative Number in C#

I would like to generate array of 10 elements with random number between (-10,10).我想生成 10 个元素的数组,其中随机数介于 (-10,10) 之间。

And scenario is array can contain positive number between (0,10) for odd positions and contain negative number between(-10,0) for even position并且场景是数组可以在 (0,10) 之间包含奇数位置的正数,并在偶数位置包含 (-10,0) 之间的负数

For Example : 1,-2,3,-4,7,-1,3,-3,2,-9例如:1,-2,3,-4,7,-1,3,-3,2,-9

And im totally stucked in generating -ve number at even places because im new in programming.而且我完全坚持在偶数地方生成 -ve 数字,因为我是编程新手。

Any Help Is Appreciated,Thanx In Advance感谢任何帮助,提前致谢

Ok, i got your point.好的,我明白你的意思了。 Try This Code试试这个代码

Random rand = new Random();
        int[] arr = new int[10];
        for(int i = 0; i < 10; i++)
        {
            if(i % 2 == 0) 
                arr[i] = rand.Next(1,10);

            else 
                arr[i] = (rand.Next(1,10)) * -1;                   
        }
        for(int i = 0; i < 10; i++)
        {
            Console.WriteLine(arr[i]);
        }

Sample Output 1 -9 9 -8 1 -4 2 -6 4 -9样本输出1 -9 9 -8 1 -4 2 -6 4 -9

Try this:试试这个:

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main (string[] args)
        {
            var random = new Random ();

            var array = new int[10];

            for (int i = 0; i < array.Length; i++)
            {
                bool isOdd = (i % 2) == 1; // check remainder

                int randomNumber = random.Next (0, 11); // 0..10

                if (isOdd) randomNumber = -randomNumber; // change sign

                array[i] = randomNumber;
            }
        }
    }
}

This is easier than all the posted answers so far.这比迄今为止所有发布的答案都容易。 Here is a basic infinite loop from which to base your specific needs.这是一个基本的无限循环,可根据您的特定需求。

    public IEnumerable<int> RandomAlternatingSequence()
    {
        var random = new Random();
        int sign = -1;

        while (true)
        {
            sign *= -1;

            yield return sign * random.Next();
        }
    }

I realize that the post is 2 years old but this may help others who come looking.我意识到这个帖子已经有 2 年的历史了,但这可能会帮助其他来找的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM