Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# Convert int to char

Posted on 2007-11-26
Medium Priority
287 Views
What does this calculation mean?
char ch;
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));

I got it from
0
Question by:JRockFL
• 2
• 2

LVL 55

Accepted Solution

Jaime Olivares earned 2000 total points
ID: 20354352
>>26 * random.NextDouble()
a decimal value between 0 and 26

>>26 * random.NextDouble() + 65
a decimal value between 26 and 91

>>Math.Floor(26 * random.NextDouble() + 65)
just the integral portion of the previous value (still is decimal type)

>>Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))
previous value converted to an integral type

>>Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
previous value converted to a character using the ASCII code

Result: a random character between 'A' and 'Z' (uppercase)

0

LVL 8

Author Comment

ID: 20354412
Thank you so much for the reply,
A couple questions...
How does 26 * random.NextDouble() equate to 0 and 26?
I was thinking it was being multiplied.
Could you also do random.Next(0,26) if decimal is not needed?

Also, do we even need to work with a decimal type?

So if we Convert.ToChar( Any number between 26 and 91) we get a random character?
0

LVL 55

Expert Comment

ID: 20354481
NextDouble() Returns a random number between 0.0 and 1.0. So you have to multiply to have a bigger range.
And yes, Next(0,26) would be better, but even better Next(26,91).
But for legibility sake, I would use

ch = (char)random.Next((int)'A', (int)'Z');
0

LVL 8

Author Comment

ID: 20354581
Thank you so much, I appreciate the help and clarity.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
###### Suggested Courses
Course of the Month13 days, 13 hours left to enroll