Hello Guest, please login or register.
Did you miss your activation email?
Login with username, password and session length.

Pages: [1]   Go Down

Author Topic: [Solved] Help translating to C#  (Read 1603 times)

0 Members and 1 Guest are viewing this topic.
[Solved] Help translating to C#
« on: April 17, 2010, 09:16:28 pm »
  • *
  • Reputation: +2/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1767
I need some help translating this random number generator in C#. Not so much the output and the for loop structure and what not, but basically how the cstdlib, and ctime would translate to C#, and the srand((unsigned)time(0)); Can anyone help me out?

C++ Code:
Code: [Select]
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand((unsigned)time(0));
int n = 0, k = 0;
// Roll 30 Times.
for (k = 0;k < 30;k++)
{
// Get the random number
n = (rand() % 4);
cout << n << endl;
}
return 0;
}
« Last Edit: April 18, 2010, 02:59:03 pm by Colbydude »
Logged
  • https://colbydude.com
Re: Help translating to C#
« Reply #1 on: April 18, 2010, 02:20:20 pm »
  • (y)(;>.<;)(y)
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 3293
Logged
Re: Help translating to C#
« Reply #2 on: April 18, 2010, 02:58:25 pm »
  • *
  • Reputation: +2/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1767
Yeah I had that originally, but I realized where my error was. I was using this code:

Code: [Select]
private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

I thought about it while talking to Min about it. Then I realized it was using the same seed since I was re-instantiating it every time I called the function. So I made random a class-wide variable, and it does what I want now. But thanks TheDarkJay.
Logged
  • https://colbydude.com
Re: [Solved] Help translating to C#
« Reply #3 on: April 18, 2010, 10:38:45 pm »
  • (y)(;>.<;)(y)
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 3293
Code: [Select]
private int RandomNumber(int min, int max)
{
    static Random random = new Random();
    return random.Next(min, max);
}

Would have solved the problem the same and used only one Random class regardless of how many instances of the class were used ^.^ (At least I'm fairly sure that's how statics in C# functions work XD)

Probably not useful for this particular problem but still...
Logged
Pages: [1]   Go Up

 


Contact Us | Legal | Advertise Here
2013 © ZFGC, All Rights Reserved



Page created in 0.021 seconds with 42 queries.

anything