0

I need to convert some "Classic ASP 3.0" code into C# using ASP.NET:

Randomize() intUP = 9 intLow = 1 intRange = intUp - intLow intRandom = CInt ((intRange * Rnd()) + intLow) Response.Write(intRandom & "<br /><br />") for i = 1 to (num) + intRandom Response.Write(intRandom & "<br />") next 

And I have tried this code:

int count; Random rnd; protected void Page_Load(object sender, EventArgs e) { rnd = new Random(); count = GetRandomInt(1, 9); for (int i = 0; i < count; i++) { Response.Write(count.ToString()); } } protected int GetRandomInt(int min, int max) { return rnd.Next(min, max); } 

But in Classic ASP 3.0, the maximum output is 9, but in C# and ASP.NET, it is much higher.

What am I missing?

What's wrong with this code?

Thank you in advance.

1 Answer 1

2

Actually the maximum number is lower in the C# code, but you are writing the numbers back to back so they are shown as one big number instead of separate numbers.

The Random.Next method returns a number that is at least as high as the first parameter, and lower than the second parameter. Calling rnd.Next(1, 9) will give you a number between 1 and 8.

You are loopin from zero and up to one less than the random number. When you write those number in the loop with nothing in between them, the output for the largest value would be:

01234567 

where the original code would instead write this for the largest value:

9 1 2 3 4 5 6 7 8 9 

To get a random number between min and max, add one to the max:

return rnd.Next(min, max + 1); 

Loop from one instead of zero, include the end value, and put something in between the numbers:

for (int i = 1; i <= count; i++) { Response.Write(count.ToString() + "<br />"); } 

Note: The random calculation in the original code is actually incorrect, as it would generate the lowest and the highest value half as often as any of the other numbers. The correct implementation would be:

intRange = intUp - intLow + 1 intRandom = Int((intRange * Rnd()) + intLow) 

The C# code mimics the correct implementation, not the incorrect one.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.