# C# random complex number for (real, imaginary number) between 100 , 200?

Here is my code in C# , but it generate same number for specific amount number like this:
180 + 152 i
180 + 152 i
180 + 152 i
180 + 152 i
180 + 152 i

any idea?

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex2
{
class Complex
{
public double real, imag;
public void Set()
{

``````        Random r = new Random();
imag = r.Next(100,200);
real = r.Next(100,200);

}

public void Write()
{
char sign;
sign = (imag > 0) ? '+' : '-';
Console.WriteLine("{0} {1} {2} i ", real, sign, Math.Abs(imag));
}

}
class Program
{
private static int n;
static void Main(string[] args)
{
Console.Write("How Many Number : ");
n = Convert.ToInt32(Console.ReadLine());

Complex[] complexArray = new Complex[n];
Random r = new Random();

for (int i= 0; i < n; ++i)
{
complexArray[i] = new Complex();
}

for (int i = 0; i < n; ++i)
{
complexArray[i].Set();
complexArray[i].Write();
}

realSort(complexArray);

Console.WriteLine();

for (int i = 0; i < n; ++i)
complexArray[i].Write();

Console.ReadKey();
}

public static void realSort(Complex[] s)
{
Complex temp;
for (int i = 1; i <= s.Length - 1; ++i)
for (int j = 0; j < s.Length - i; ++j)
if (s[j].real > s[j + 1].real)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
``````

}

## Comments

• Israel
edited November 2015

Hey,

What you want to do is change the

`public void set()`

To:
`public void Set(Random r)`

And when you call it use:

`complexArray[i].Set(r);`

And of course in `public void Set(Random r)`
lose the `Random r = new Random();`

That's it, it works!

Explanation:

Each time you use "new Random()" it resets, that why when you create more than one random number, you should keep the Random instance and reuse it.

Sign In or Register to comment.

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!