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

4개 자습서로 구성된 이 시리즈에서는 수학 퀴즈를 빌드합니다. 퀴즈는 퀴즈를 푸는 사람이 지정된 시간 이내에 답변을 시도하는 4가지 난수 수학 문제를 포함합니다.

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

두 번째 자습서에서는 다음 작업을 수행하는 방법을 알아봅니다.

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

사전 요구 사항

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

난수 더하기 문제 만들기

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

  2. Form1 양식을 선택합니다.

  3. 메뉴 모음에서 보기>코드를 선택합니다. 폼의 숨김 코드를 볼 수 있도록 사용 중인 프로그래밍 언어에 따라 Form1.cs 또는 Form1.vb가 표시됩니다.

  4. 코드 위쪽에 new 문을 추가하여 Random 개체를 만듭니다.

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

중요

이 페이지의 오른쪽 위에 있는 프로그래밍 언어 컨트롤을 사용하여 C# 코드 조각 또는 Visual Basic 코드 조각을 볼 수 있습니다.

Programming language control for Microsoft Learn

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

프로그램을 실행하면 양식이 시작됩니다. 양식의 숨김 코드가 Random 개체를 만들고 이름을 randomizer로 지정합니다.

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

  1. 폼에 두 개의 정수 변수를 추가하고 이름을 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()라는 메서드를 추가합니다. 이 메서드는 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() 메서드를 Random 개체와 함께 사용하는 경우 51 미만(0~50)의 난수가 반환됩니다. 이 코드는 randomizer.Next(51)를 호출하여 두 개의 난수가 0~100의 답변에 합산되도록 합니다.

이러한 문을 자세히 살펴봅니다.

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

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

난수 빼기, 곱하기, 나누기 문제 만들기

다음 단계는 변수를 선언하고 다른 수학 문제에 난수를 제공하는 것입니다.

  1. 나머지 수학 문제의 정수 변수를 양식에서 더하기 문제 변수 뒤에 추가합니다. 코드는 다음 샘플과 같습니다.

    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. “빼기 문제 채우기” 주석으로 시작해서 다음 코드를 추가하여 StartTheQuiz() 메서드를 수정합니다.

    /// <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 디자이너에서 Start the quiz 단추를 두 번 클릭하거나, 이 단추를 선택한 후 Enter 키를 선택합니다. 양식의 코드가 나타나고 새 메서드가 표시됩니다.

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

  2. 이벤트 처리기가 퀴즈를 시작하도록 다음과 같은 2개 문을 추가합니다.

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

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

앱을 실행합니다.

  1. 코드를 저장합니다.

  2. 앱을 실행한 후 Start the quiz를 선택합니다. 다음 스크린샷과 같이 난수 수학 문제가 나타납니다.

    Screenshot that shows random values in all four math problems. The Start the quiz button appears dimmed.

다음 단계

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