다음을 통해 공유


자습서: 수학 퀴즈 WinForms 앱에 수학 문제 추가

이 4개의 자습서 시리즈에서는 수학 퀴즈를 작성합니다. 퀴즈에는 퀴즈 응시자에서 지정된 시간 내에 대답하려고 시도하는 네 가지 임의 수학 문제가 포함되어 있습니다.

컨트롤은 C# 또는 Visual Basic 코드를 사용합니다. 이 두 번째 자습서에서는 난수를 기반으로 하는 수학 문제에 대한 코드를 추가하여 퀴즈를 어렵게 만듭니다. 또한 문제를 채우기 위해 StartTheQuiz() 이름이 지정된 메서드를 만듭니다.

이 두 번째 자습서에서는 다음 방법을 알아봅니다.

  • 수학 문제에 사용할 Random 개체를 만드는 코드를 작성합니다.
  • 시작 단추에 대한 이벤트 처리기를 추가합니다.
  • 퀴즈를 시작하는 코드를 작성합니다.

필수 구성 요소

이 자습서는 이전 자습서인 수학 퀴즈 WinForms 앱을 기반으로 합니다. 해당 자습서를 완료하지 않은 경우 먼저 이 자습서를 진행합니다.

임의 추가 문제 만들기

  1. Visual Studio 프로젝트에서 Windows Forms 디자이너 선택합니다.

  2. 양식을 선택하세요, Form1.

  3. 메뉴 모음에서 보기>코드을(를) 선택합니다. 사용 중인 프로그래밍 언어에 따라 Form1.cs 또는 Form1.vb 표시되므로 양식 뒤에 있는 코드를 볼 수 있습니다.

  4. Form1.cs 또는 Form1.vb코드 맨 위에 new 문을 추가하여 Random 개체를 만듭니다.

    public partial class Form1 : Form
    {
        // Create a Random object called randomizer 
        // to generate random numbers.
        Random randomizer = new Random();
    

이와 같은 new 문을 사용하여 단추, 레이블, 패널, OpenFileDialogs, ColorDialogs, SoundPlayers, Randoms 및 폼을 만들 수 있습니다. 이러한 항목을 개체라고 합니다.

프로그램을 실행하면 양식이 시작됩니다. 이 코드는 Random 객체를 만들고 이를 randomizer라고 부릅니다.

퀴즈에는 각 문제에 대해 만드는 난수를 저장하는 변수가 필요합니다. 변수를 사용하기 전에 해당 이름 및 데이터 형식을 나열하는 것을 의미하는 변수를 선언합니다.

  1. 폼에 두 개의 정수 변수를 추가하고, Form1.cs 또는 Form1.vb에서 이 변수 이름을 각각 addend1addend2로 지정합니다.

    메모

    C#에서는 정수 변수를 int라고 하고, Visual Basic에서는 Integer라고 합니다. 이러한 종류의 변수는 -2147483648 2147483647 양수 또는 음수를 저장하며 소수점 이하의 정수만 저장할 수 있습니다.

    다음 코드와 같이 Random 개체를 추가하는 것과 비슷한 구문을 사용하여 정수 변수를 추가합니다.

    // Create a Random object called randomizer 
    // to generate random numbers.
    Random randomizer = new Random();
    
    // These integer variables store the numbers 
    // for the addition problem. 
    int addend1;
    int addend2;
    

  1. 이름이 StartTheQuiz()Form1.cs 또는 Form1.vb메서드를 추가합니다. 이 메서드는 Random 개체의 Next() 메서드를 사용하여 레이블에 대한 난수를 생성합니다. StartTheQuiz() 결국 모든 문제를 채운 다음 타이머를 시작하므로 이 정보를 요약 주석에 추가합니다. 함수는 다음 코드와 같이 표시됩니다.

    /// <summary>
    /// Start the quiz by filling in all of the problems
    /// and starting the timer.
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        // Generate two random numbers to add.
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers
        // into strings so that they can be displayed
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
        // 'sum' is the name of the NumericUpDown control.
        // This step makes sure its value is zero before
        // adding any values to it.
        sum.Value = 0;
    }
    

randomizer.Next(51)호출하는 경우와 같이 임의 개체와 함께 Next() 메서드를 사용하면 51보다 작거나 0에서 50 사이의 난수를 얻습니다. 이 코드는 두 난수가 0에서 100 사이의 답변에 추가되도록 randomizer.Next(51) 호출합니다.

이러한 진술들을 좀 더 자세히 살펴보세요.

plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

이러한 문장은 두 개의 난수를 표시하도록 plusLeftLabelplusRightLabelText 속성을 설정합니다. 레이블 컨트롤은 텍스트 형식으로 값을 표시하고 프로그래밍에서는 문자열에 텍스트를 저장합니다. 각 정수의 ToString() 메서드는 정수를 레이블이 표시할 수 있는 텍스트로 변환합니다.

임의 빼기, 곱하기 및 나누기 문제 만들기

다음 단계는 변수를 선언하고 다른 수학 문제에 대한 임의 값을 제공하는 것입니다.

  1. 추가 문제 변수 뒤의 나머지 수학 문제에 대한 정수 변수를 폼에 추가합니다. Form1.cs 또는 Form1.vb 코드는 다음 샘플과 같습니다.

    public partial class Form1 : Form
    {
        // Create a Random object called randomizer 
        // to generate random numbers.
        Random randomizer = new Random();
    
        // These integer variables store the numbers 
        // for the addition problem. 
        int addend1;
        int addend2;
    
        // These integer variables store the numbers 
        // for the subtraction problem. 
        int minuend;
        int subtrahend;
    
        // These integer variables store the numbers 
        // for the multiplication problem. 
        int multiplicand;
        int multiplier;
    
        // These integer variables store the numbers 
        // for the division problem. 
        int dividend;
        int divisor;
    

  1. Form1.cs 또는 Form1.vbStartTheQuiz() 메서드를 수정하여, "빼기 문제 채우기" 주석으로 시작하는 다음 코드를 추가합니다.

    /// <summary>
    /// Start the quiz by filling in all of the problem 
    /// values and starting the timer. 
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        // Generate two random numbers to add.
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers
        // into strings so that they can be displayed
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
        // 'sum' is the name of the NumericUpDown control.
        // This step makes sure its value is zero before
        // adding any values to it.
        sum.Value = 0;
    
        // Fill in the subtraction problem.
        minuend = randomizer.Next(1, 101);
        subtrahend = randomizer.Next(1, minuend);
        minusLeftLabel.Text = minuend.ToString();
        minusRightLabel.Text = subtrahend.ToString();
        difference.Value = 0;
    
        // Fill in the multiplication problem.
        multiplicand = randomizer.Next(2, 11);
        multiplier = randomizer.Next(2, 11);
        timesLeftLabel.Text = multiplicand.ToString();
        timesRightLabel.Text = multiplier.ToString();
        product.Value = 0;
    
        // Fill in the division problem.
        divisor = randomizer.Next(2, 11);
        int temporaryQuotient = randomizer.Next(2, 11);
        dividend = divisor * temporaryQuotient;
        dividedLeftLabel.Text = dividend.ToString();
        dividedRightLabel.Text = divisor.ToString();
        quotient.Value = 0;
    

이 코드는 Random 클래스의 Next() 메서드를 추가 문제가 수행하는 방식과 약간 다르게 사용합니다. Next() 메서드에 두 개의 값을 지정하면 첫 번째 값보다 크거나 같고 두 번째 값보다 작은 난수를 선택합니다.

두 인수와 함께 Next() 메서드를 사용하면 빼기 문제에 긍정적인 대답이 있고, 곱하기 답변이 최대 100이고, 나누기 답변이 분수가 아닌지 확인할 수 있습니다.

시작 단추에 이벤트 처리기 추가

이 섹션에서는 시작 단추를 선택할 때 퀴즈를 시작하는 코드를 추가합니다. 단추 선택과 같은 이벤트에 대한 반응으로 실행되는 코드를 이벤트 처리기라고 합니다.

  1. windows Forms 디자이너 퀴즈 시작 단추를 두 번 클릭하거나 선택한 다음 입력을 선택합니다. 폼의 코드가 나타나고 새 메서드가 표시됩니다.

    이러한 작업은 시작 단추에 click 이벤트 처리기를 추가합니다. 퀴즈를 들이는 사용자가 이 단추를 선택하면 앱은 이 새 메서드에 추가할 코드를 실행합니다.

  2. 이벤트 처리기가 퀴즈를 시작할 수 있도록 다음 두 문을 추가합니다.

    private void startButton_Click(object sender, EventArgs e)
    {
        StartTheQuiz();
        startButton.Enabled = false;           
    }
    

첫 번째 문장은 새 StartTheQuiz() 메서드를 호출합니다. 두 번째 문은 퀴즈를 진행하는 동안 퀴즈 풀이자가 단추를 선택할 수 없도록 startButton 컨트롤의 Enabled 속성을 false로 설정합니다.

앱 실행

  1. 코드를 저장합니다.

  2. 앱을 실행하고 나서 퀴즈 시작을 선택합니다. 다음 스크린샷과 같이 임의 수학 문제가 나타납니다.

    네 가지 수학 문제의 임의 값을 보여 주는 스크린샷 퀴즈 시작 단추가 흐리게 표시됩니다.

다음 단계

다음 자습서로 이동하여 수학 퀴즈에 타이머를 추가하고 사용자 답변을 확인합니다.

자습서 3부: 수학 퀴즈 WinForms 앱 타이머 컨트롤 추가