Choosing random places in C#

2019-08-20 09:01发布

Hi I'm developing a simple -multiple choices- quiz program using visual studio. (C#)

I want to make the choices with radio buttons, in which each radio button has a - randomly selected answer- and one of them is the correct one.

I filled an array with the all possible answers. And I want to know how can I make the right answer not in the same place every time?

so how can I make the right answer goes for a random place? and the other places selects other random numbers from the array which are not the right one. :D

I know my question is not that clear I don't know how to explain. ><

2条回答
女痞
2楼-- · 2019-08-20 09:15

First, select your right answer, then randomly select an index and assign your right answer to the random radio button.

Fill the other radio buttons with random answers.

Tip: store your radio buttons in an list to facilitate this operation. You begin by filling the list with all your radio buttons, then remove them from the list when they're filled with an answer, this way you don't have to handle "which index did I put the right answer in" or "complicated code that references manually the controls by name"

Edit: As pointed out by Alexei Levenkov in another answer, see this thread for more information on how to generate random numbers properly

Assuming a Random random declared in your app

List<RadioButton> buttons = new List<RadioButton>();
buttons.Add(answer);
buttons.Add(answer2);
buttons.Add(answer3);
buttons.Add(answer4);

int goodAnswerPos = random.Next(buttons.Count);
buttons[goodAnswerPos].Text = "Good Answer";
buttons.RemoveAt(goodAnswerPos);

foreach (RadioButton button in buttons)
{
    button.Text = "Randomly Selected Wrong Answer";
}

Storing the control at buttons[goodAnswerPos] will allow you to know if the user selected the right one when he submits the answer.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-20 09:27

use the c# Random() class, and index your array with Next

Random r = new Random();

choice = possibleChoices[r.Next(possibleChoices.Length-1)];

then you can overwrite one of the wrong choices with the correct choice

radioButtons[r.Next(radioButtons.Length-1)] = correctAnswer;

documentation

查看更多
登录 后发表回答