Share via


Paso 6: Agregar un problema de resta

Para agregar un problema de resta, necesita:

  • Almacenar los valores de resta.

  • Generar números aleatorios para el problema (y asegurarse de que la respuesta esté comprendida entre 0 y 100).

  • Actualizar el método que comprueba las respuestas para que compruebe también el nuevo problema de resta.

  • Actualizar el controlador eventos Tick del temporizador para que rellene la respuesta correcta cuando se agote el tiempo.

Para agregar un problema de resta

  1. En primer lugar, se necesita un lugar donde almacenar los valores, así que agregue dos valores de tipo int (Enteros) para el problema de resta al formulario.El nuevo código aparece entre los enteros de suma y el entero del temporizador.El código debe tener este aspecto.

    Public Class Form1
    
        ' Create a Random object to generate random numbers.
        Dim randomizer As New Random
    
        ' These Integers will store the numbers
        ' for the addition problem.
        Dim addend1 As Integer
        Dim addend2 As Integer
    
        ' These Integers will store the numbers
        ' for the subtraction problem.
        Dim minuend As Integer
        Dim subtrahend As Integer
    
        ' This Integer will keep track of the time left.
        Dim timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object to generate random numbers.
        Random randomizer = new Random();
    
        // These ints will store the numbers
        // for the addition problem.
        int addend1;
        int addend2;
    
        // These ints will store the numbers
        // for the subtraction problem.
        int minuend;
        int subtrahend;
    
        // This int will keep track of the time left.
        int timeLeft;
    

    Nota

    Los nombres de los nuevos valores int (minuend y subtrahend, minuendo y sustraendo) no son términos de Visual C#, ni siquiera términos de programación.Se trata de los nombres utilizados tradicionalmente en aritmética para el número que se resta (el substraendo) y el número del que se resta (el minuendo).La diferencia es el minuendo menos el sustraendo.Puede utilizar otros nombres, porque el programa no requiere nombres específicos para los valores de tipo int, los controles, los componentes o los métodos.Hay algunas reglas (por ejemplo, los nombres no pueden comenzar con dígitos), pero en general, podría utilizar nombres como x1, x2, x3, x4, etc.Sin embargo, sería difícil leer el código y casi imposible realizar el seguimiento de los problemas.Más adelante en este tutorial utilizaremos los términos tradicionales para la multiplicación (multiplicand × multiplier = product, multiplicando × multiplicador = producto) y la división (dividend ÷ divisor = quotient, dividendo ÷ divisor = cociente).

  2. A continuación, modifique el método StartTheQuiz() para rellenar un problema de resta aleatorio.El nuevo código aparece tras el comentario "Fill in the subtraction problem".El código debe tener este aspecto.

    ''' <summary>
    ''' Start the quiz by filling in all of the problems
    ''' and starting the timer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
        plusLeftLabel.Text = addend1.ToString
        plusRightLabel.Text = addend2.ToString
        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
    
        ' Start the timer.
        timeLeft = 30
        timeLabel.Text = "30 seconds"
        Timer1.Start()
    
    End Sub
    
    /// <summary>
    /// Start the quiz by filling in all of the problems
    /// and starting the timer.
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
        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;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    Este código utiliza el método Next() de la clase Random de una forma algo distinta.Al darle dos valores, elige al azar uno que sea mayor o igual que el primero y menor que el segundo.La siguiente línea elige un número aleatorio del 1 al 100 y lo almacena en el minuendo.

    minuend = randomizer.Next(1, 101)
    
    minuend = randomizer.Next(1, 101);
    

    Se puede llamar al método Next() de la clase Random de varias formas.Cuando se puede llamar a un método de más de una manera, se denomina método sobrecargado. Puede utilizar IntelliSense para explorar esta posibilidad.Fijémonos de nuevo en la información sobre herramientas de la ventana IntelliSense del método Next().

    Información sobre herramientas de la ventana IntelliSense

    Método Next

    Observe que la información sobre herramientas muestra (+ 2 sobrecargas).Esto significa que hay dos formas más de llamar al método Next().Al escribir el nuevo código para el método StartTheQuiz(), puede ver más información.En cuanto escriba randomizer.Next(, aparecerá la ventana IntelliSense.Presione las teclas de dirección ARRIBA y ABAJO para recorrer cíclicamente las sobrecargas, como se muestra en la siguiente imagen.

    Sobrecargas en la ventana IntelliSense

    Sobrecargas de la ventana de Intellisense

    La de la imagen anterior es la que deseamos utilizar, porque permite especificar un valor mínimo y máximo.

  3. Modifique el método CheckTheAnswer() para que compruebe si la respuesta de la resta es correcta.El código debe tener este aspecto.

    ''' <summary>
    ''' Check the answer to see if the user got everything right.
    ''' </summary>
    ''' <returns>True if the answer's correct, false otherwise.</returns>
    ''' <remarks></remarks>
    Public Function CheckTheAnswer() As Boolean
    
        If ((addend1 + addend2 = sum.Value) AndAlso (minuend - subtrahend = difference.Value)) Then
            Return True
        Else
            Return False
        End If
    
    End Function
    
    /// <summary>
    /// Check the answer to see if the user got everything right.
    /// </summary>
    /// <returns>True if the answer's correct, false otherwise.</returns>
    private bool CheckTheAnswer()
    {
        if ((addend1 + addend2 == sum.Value)
            && (minuend - subtrahend == difference.Value))
            return true;
        else
            return false;
    }
    

    && es el operador logical and de Visual C#.En Visual Basic, el operador equivalente es AndAlso.Equivale a decir, "Si addend1 más addend2 es igual al valor de la suma NumericUpDown, y si el minuendo menos el sustraendo es igual al valor de la diferencia NumericUpDown". El método CheckTheAnswer() devuelve true únicamente si el problema de suma es correcto y el problema de resta es correcto.

  4. Cambie la última parte del controlador de evento Tick del temporizador de modo que rellene la respuesta correcta cuando se agote el tiempo.El código debe tener este aspecto.

    Else
        ' If the user ran out of time, stop the timer, show
        ' a MessageBox, and fill in the answers.
        Timer1.Stop()
        timeLabel.Text = "Time's up!"
        MessageBox.Show("You didn't finish in time.", "Sorry")
        sum.Value = addend1 + addend2
        difference.Value = minuend - subtrahend
        startButton.Enabled = True
    End If
    
    else
    {
        // If the user ran out of time, stop the timer, show
        // a MessageBox, and fill in the answers.
        timer1.Stop();
        timeLabel.Text = "Time's up!";
        MessageBox.Show("You didn't finish in time.", "Sorry");
        sum.Value = addend1 + addend2;
        difference.Value = minuend - subtrahend;
        startButton.Enabled = true;
    }
    
  5. Guarde y ejecute el código.Ahora, el programa deberá incluir un problema de resta, como se muestra en la siguiente imagen.

    Cuestionario de matemáticas con un problema de resta

    Prueba matemática con un problema de resta

Para continuar o revisar