No Description
Rafael Arce Nazario ac8dd282af QuadraticFormula.cpp edited online with Bitbucket - removed Ive's comments 8 years ago
images Resease version initial commit 9 years ago
resources Resease version initial commit 9 years ago
QuadraticFormula.cpp QuadraticFormula.cpp edited online with Bitbucket - removed Ive's comments 8 years ago
QuadraticFrog.pro Turned off qDebug messages 8 years ago
README.md Some fixes to the README. Removed two diagnostics, added one 8 years ago
frog.cpp Changes in the sources, updated README 9 years ago
frog.h Changes in the sources, updated README 9 years ago
main.cpp Resease version initial commit 9 years ago
mainwindow.cpp Changes in the sources, updated README 9 years ago
mainwindow.h Changes in the sources, updated README 9 years ago
mainwindow.ui Resease version initial commit 9 years ago

README.md

English | Español

Expresiones aritméticas - Sapo Cuadrático

main1.png main2.png main4.png

Las expresiones aritméticas son parte esencial de casi cualquier algoritmo que resuelve un problema útil. Por lo tanto, implementar expresiones aritméticas correctamente es una destreza básica en cualquier lenguaje de programación de computadoras. En esta experiencia de laboratorio practicarás la implementación de expresiones aritméticas en C++ escribiendo ecuaciones para la fórmula cuadrática y así completar el código para un juego en el que un sapito brinca de una hoja a otra.

Objetivos:

  1. Implementar expresiones aritméticas en C++ para definir la trayectoria del brinco de un sapito en un juego.
  2. Utilizar constantes adecuadamente.
  3. Definir variables utilizando tipos de datos adecuados.
  4. Convertir el valor de un dato a otro tipo cuando sea necesario.

Pre-Lab:

Antes de llegar al laboratorio debes:

  1. Haber repasado los siguientes conceptos:

    a. implementar expresiones aritméticas en C++

    b. tipos de datos nativos de C++ (int, float, double, char)

    c. usar “type casting” para covertir el valor de una variable a otro tipo dentro de expresiones.

    d. utilizar funciones y constantes aritméticas de la biblioteca cmath

    e. ecuaciones cuadráticas y sus gráficas.

  2. haber estudiado los conceptos e instrucciones para la sesión de laboratorio.

  3. haber tomado el quiz Pre-Lab que se encuentra en Moodle.



Fórmula cuadrática

Una ecuación cuadrática tiene la forma

$$y = a x^2+ b x + c,$$

donde $$a, b, c$$ son números reales y $$a\not=0$$. La gráfica de una ecuación cuadrática es una parábola que abre hacia arriba si $$a > 0$$ y abre hacia abajo si $$a < 0$$.

Una gráfica interseca el eje de $$x$$ cuando $$y=0$$. Por lo tanto, si una parábola interseca el eje de $$x$$, los intersectos están dados por las soluciones reales de la ecuación

$$0 = a x^2 + b x + c.$$

Las soluciones a la ecuación anterior se pueden obtener utilizando la fórmula cuadrática:

$$x=\frac{-b±\sqrt{b^2-4ac}}{2a}.$$

Nota que si el discriminante $$b^2-4ac$$ de la fórmula cuadrática es negativo, los valores de $$x$$ serán números imaginarios y no se pueden graficar en el plano cartesiano porque los puntos $$(x,y)$$ en este plano tienen coordenadas que son números reales. Por lo tanto, si el discriminante es negativo, la parábola no interseca el eje de $$x$$. Si el discriminate es igual a $$0$$, entonces la parábola interseca el eje de $$x$$ en un solo punto (solo el vértice toca el eje de $$x$$).

Si el discriminante es positivo, la fórmula cuadrática nos dá dos soluciones a la ecuación $$0 = a x^2 + b x + c$$ y estas soluciones son los intersectos en el eje de $$x$$. Por ejemplo, supón que la fórmula cuadrática nos dá dos valores

$$x=x_1$$ $$x=x_2$$

Entonces,

$$a x^2 + b x + c = a(x-x_1)(x-x_2),$$

donde $$x_1$$ y $$x_2$$ son los cortes en el eje de $$x$$. Si $$a<0$$, la gráfica de la parábola será similar a la de la Figura 1.


parabola.png

Figura 1. Parábola que abre hacia abajo e interseca el eje de $$x$$ en $$x_1$$ y $$x_2$$.


Nota que la ecuación

$$y=-(x-x_1)(x-x_2)$$

es una ecuación cuadrática cuya parábola abre hacia abajo e interseca el eje de $$x$$ en $$x_1$$ y $$x_2$$. Por ejemplo, la ecuación

$$y=-(x+2)(x-3)=-x^2+x+6$$

es una ecuación cuadrática cuya parábola abre hacia abajo e interseca el eje de $$x$$ en $$x_1=-2$$ y $$x_2=3$$. Nota que, en esta ecuación, los valores de $$a,b,c$$ son $$a=-1, \ b=1, \ c=6$$.



!INCLUDE “../../eip-diagnostic/quadratic-frog/es/diag-quadratic-frog-01.html”

!INCLUDE “../../eip-diagnostic/quadratic-frog/es/diag-quadratic-frog-08.html”

!INCLUDE “../../eip-diagnostic/quadratic-frog/es/diag-quadratic-frog-09.html”



Sesión de laboratorio:

Ejercicio 1

En este ejercicio implementarás la fórmula cuadrática para completar un juego en el que un sapito brinca de una hoja a otra. Asumirás que las hojas están localizadas sobre el eje de $$x$$ y que el brinco del sapito estará determinado por una parábola que abre hacia abajo. Si quieres que el sapito brinque de hoja a hoja, debes hayar una ecuación cuadrática cuya parábola abra hacia abajo e interseque el eje de $$x$$ en los lugares donde están localizadas las hojas. Tu tarea es escribir las ecuaciones para la fórmula cuadrática.

Instrucciones

  1. Carga a Qt el proyecto QuadraticFrog haciendo doble “click” en el archivo QuadraticFrog.pro que se encuentra en la carpeta Documents/eip/Expressions-QuadraticFrog de tu computadora. También puedes ir a http://bitbucket.org/eip-uprrp/expressions-quadraticfrog para descargar la carpeta QuadraticFrog a tu computadora.

  2. Configura el proyecto y ejecuta el programa marcando la flecha verde en el menú de la izquierda de la ventana de Qt Creator. El programa te dará un mensaje que dice que la fórmula cuadrática está mal escrita. Esto sucede porque el programa tiene instrucciones que prueban el programa y verifican que la implementación del código esté correcta. Tu programa aún no tiene las instrucciones para evaluar la fórmula cuadrática y por esto sale el mensaje.

  3. En el archivo QuadraticFormula.cpp (en Sources) escribirás las ecuaciones para la fórmula cuadrática. En la función QuadraticPlus añade la ecuación

    $$result=\frac{-b+\sqrt{b^2-4ac}}{2a},$$

    y en la función QuadraticMinus añade la ecuación

    $$result=\frac{-b-\sqrt{b^2-4ac}}{2a}.$$

    Los otros archivos del proyecto tienen código que hará pruebas a las ecuaciones que escribiste evaluando varios valores para $$a, b ,c$$ y verificando que el resultado que producen las ecuaciones es el esperado. La validación del código de un programa es una parte importante de el desarrollo de programas y proyectos.

  4. Ejecuta el programa marcando el botón verde en el menú de la izquierda. Si las ecuaciones que escribiste están correctas, deberá aparecer una ventana parecida a la Figura 2.


    figure2.png

    Figura 2. Ventana del juego Quadratic Frog.


  5. Entrega el archivo QuadraticFormula.cpp que contiene las funciones las funciones QuadraticPlus y QuadraticMinus utilizando “Entrega 1” en Moodle. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.

  6. Para jugar, el sapito deberá brincar de una hoja a otra. Nota que las hojas tienen valores para $$x_1$$ y $$x_2$$. Estos valores representan los intercectos en el eje de $$x$$ de la parábola. Debes entrar los valores para los coeficientes $$a,b,c$$ de la ecuación cuadrática de modo que la gráfica sea una parábola que abra hacia abajo e interseque el eje de $$x$$ en los valores $$x_1, x_2$$ que salen en las hojas. Puedes obtener los valores de $$a,b,c$$ notando que

$$a x^2 + b x + c = a(x-x_1)(x-x_2),$$

como en la explicación de arriba.

Ejercicio 2

En este ejercicio escribirás un programa para obtener el promedio de puntos para la nota de un estudiante.

Supón que todos los cursos en la Universidad de Yauco son de 3 créditos y que las notas tienen las siguientes puntuaciones: $$A = 4$$ puntos por crédito; $$B = 3$$ puntos por crédito; $$C = 2$$ puntos por crédito; $$D = 1$$ punto por crédito y $$F = 0$$ puntos por crédito.

Instrucciones

  1. Crea un nuevo proyecto “Non-Qt” llamado Promedio. Tu función main() contendrá el código necesario para pedirle al usuario el número de A’s, B’s, C’s, D’s y F’s obtenidas por el estudiante y computar el promedio de puntos para la nota (GPA por sus siglas en inglés).

  2. Tu código debe definir las constantes $$A=4, B=3, C=2, D=1, F=0$$ para la puntuación de las notas, y pedirle al usuario que entre los valores para las variables $$NumA$$, $$NumB$$, $$NumC$$, $$NumD$$, $$NumF$$. La variable $$NumA$$ representará el número de cursos en los que el estudiante obtuvo $$A$$, $$NumB$$ representará el número de cursos en los que el estudiante obtuvo $$B$$, etc. El programa debe desplegar el GPA del estudiante en una escala de 0 a 4 puntos.

    Ayudas:

    1. El promedio se obtiene sumando las puntuaciones correspondientes a las notas obtenidas (por ejemplo, una A en un curso de 3 créditos tiene una puntuación de 12), y dividiendo esa suma por el número total de créditos.

    2. Recuerda que, en C++, si divides dos números enteros el resultado se “truncará” y será un número entero. Utiliza “type casting”: `static_cast<tipo>(expresión)’ para resolver este problema.

  3. Verifica tu programa calculando el promedio de un estudiante que tenga dos A y dos B; ¿qué nota tendría este estudiante, A o B (la A va desde 3.5 a 4.0)?. Cuando tu programa esté correcto, guarda el archivo main.cpp y entrégalo utilizando “Entrega 2” en Moodle. Recuerda seguir las instrucciones en el uso de nombres y tipos para las variables, incluir el nombre de los programadores, documentar tu programa y utilizar buenas prácticas de programación.



English | Español

Arithmetic Expressions - Quadratic Frog

main1.png main2.png main4.png

Arithmetic expressions are an essential part of almost any algorithm that solves a useful problem. Therefore, a basic skill in any computer programming language is to implement arithmetic expressions correctly. In this laboratory experience you will practice the implementation of arithmetic expressions in C++ by writing equations for the quadratic formula and complete the code for a game in which a frog jumps from leaf to leaf.

Objectives:

  1. To implement arithmetic expressions in C++ to produce graphs.
  2. To use constants adequately.
  3. To define variables using adequate data types.
  4. To cast a data value to another type when necessary.

Pre-Lab:

Before you get to the laboratory you should have:

  1. Reviewed the following concepts:

    a. implementing arithmetic expressions in C++.

    b. native data types in C++ (int, float, double)

    c. using “type casting” to cast the value of variables to other data types within expressions.

    d. using arithmetic functions and constants from the cmath library.

    e. quadratic equations and their graphs.

  2. Studied the concepts and instructions for the laboratory session.

  3. Taken the Pre-Lab quiz that can be found in Moodle.



Quadratic Formula

A quadratic equation has a form

$$y = a x^2+ b x + c,$$

where $$a, b, c$$ are real numbers and $$a\not=0$$. The graph of a quadratic equation is a parabola that opens up if $$a > 0$$ and opens dawn if $$a < 0$$.

A graph intersects the $$x$$-axis when $$y=0$$. Therefore, if a parabola intersects the $$x$$-axis, the intersects are given by the real solutions to the equation

$$0 = a x^2 + b x + c.$$

The solutions to the previous equation can be obtained using the quadratic formula:

$$x=\frac{-b±\sqrt{b^2-4ac}}{2a}.$$

Note that if the discriminant $$b^2-4ac$$ of the quadratic formula is negative, the values of $$x$$ are complex numbers and are not plotted in the Cartesian plane. Therefore, if the discriminant is negative, the parabola does not intersect the $$x$$-axis. If the discriminant is equal to $0$, then the parabola intersects the $$x$$-axis in only one point (only the vertex touches the $$x$$-axis).

If the discriminant is positive, the quadratic formula gives two solutions to the equation $$0 = a x^2 + b x + c$$ and these solutions are the intersects in the $$x$$-axis. For example, suppose that the quadratic formula gives two values

$$x=x_1$$ $$x=x_2$$

Then,

$$a x^2 + b x + c = a(x-x_1)(x-x_2),$$

where $$x_1$$ and $$x_2$$ are the intersects in the $$x$$-axis. If $$a<0$$, the graph of the parabola will be similar to the one in Figure 1.


parabola.png

Figure 1. Parabola that opens down and intersects the $$x$$-axis in $$x_1$$ and $$x_2$$.


Note that the equation

$$y=-(x-x_1)(x-x_2)$$

is a quadratic equation and its parabola opens down and intersects the $$x$$-axis in $$x_1$$ and $$x_2$$. For example, the equation

$$y=-(x+2)(x-3)=-x^2+x+6$$

is a quadratic equation with a parabola that opens down and intersects the $$x$$-axis at $$x_1=-2$$ and $$x_2=3$$. Note that, in this equation, the values for $$a, b, c$$ are $$a=-1, \ b=1, \ c=6$$.



!INCLUDE “../../eip-diagnostic/quadratic-frog/en/diag-quadratic-frog-01.html”

!INCLUDE “../../eip-diagnostic/quadratic-frog/en/diag-quadratic-frog-08.html”

!INCLUDE “../../eip-diagnostic/quadratic-frog/en/diag-quadratic-frog-09.html”


Laboratory session:

Exercise 1

In this exercise you will implement the quadratic formula to complete a game in which a frog leaps from one leaf to another. You will assume that the leaves are in the $$x$$-axis and that the leap is determined by a parabola that opens down. If you want the frog to leap from leaf to leaf, you must find a quadratic equation with a parabola that opens down and intersects the $$x$$-axis in the places where the leaves are located. Your task is to write the equations for the quadratic formula.

Instructions

  1. Double click the file QuadraticFrog.pro that is contained in the Documents/eip/Expressions-QuadraticFrog folder to load the project QuadraticFrog into Qt. You can also download the folder Expressions-QuadraticFrog from http://bitbucket.org/eip-uprrp/expressions-quadraticfrog.

  2. Configure the project and run the program by clicking the green arrow in the menu on the left side of the Qt Creator window. The program will display a message saying that the quadratic formula is wrong. This happens because the program has testing instructions that verify that the code implementation is correct. Your program is missing the code for the quadratic formula and this is why the message is displayed.

  3. You will write the equations for the quadratic formula in the file In the file QuadraticFormula.cpp (in Sources). In the function QuadraticPlus add the equation

    $$result=\frac{-b+\sqrt{b^2-4ac}}{2a},$$

    and in the function QuadraticMinus add the equation

    $$result=\frac{-b-\sqrt{b^2-4ac}}{2a}.$$

    The other files of the project have code that will test your equations by evaluating several choices for $$a, b, c$$ and verifying that the equations produce the expected result. Code validation is an important part of software development.

  4. Run the program by clicking the green arrow in the menu on the left side of the Qt Creator window. If your equations are implemented correclty, you should obtain a window similar to the one in Figure 2.


    figure2.png

    Figure 2. Window of the game Quadratic Frog.


  5. Use “Deliver 1” in Moodle to submit the file QuadraticFormula.cpp containing the code with the functions QuadraticPlus and QuadraticMinus. Remember to use good programming practices, to include the names of the programmers and to document your program.

  6. To play, the frog should leap jump from one leaf to another. Note that the leaves have values for $$x_1$$ and $$x_2$$. These values represent the intersects of the parabola with the $$x$$-axis. You should input the values for the coefficients $$a, b, c$$ of the quadratic equation so that its graph that is a parabola that opens down and intersects the $$x$$-axis in the values $$x_1, x_2$$ shown in the leaves. You can obtain these values noting that

$$a x^2 + b x + c = a(x-x_1)(x-x_2),$$

as in the explanation above.

Exercise 2

In this exercise you will write a program to obtain a student’s grade point average (GPA).

Suppose that all courses in Cheo’s University are 3 credits each and have the following point values: $$A = 4$$ points per credit; $$B = 3$$ points per credit; $$C = 2$$ points per credit; $$D = 1$$ point per credit y $$F = 0$$ points per credit.

Instructions

  1. Start a new “Non-Qt” project called “Average”. Your main() function will contain the necessary code to ask the user for the number of A’s, B’s, C’s, D’s and F’s obtained and compute the grade point average (GPA).

  2. Your code should define the constants $$A=4, B=3, C=2, D=1, F=0$$ for the points per credit, and ask the user to input the values for the variables $$NumA$$, $$NumB$$, $$NumC$$, $$NumD$$, $$NumF$$. The variable $$NumA$$ represents the number of courses in which the student obtained A, $$NumB$$ represents the number of courses in which the student obtained B, etc. The program should display the GPA using the 0-4 point scale.

    Hints:

    1. You can obtain the GPA by adding the credit points corresponding to the grades (for example, an A in a 3 credit course has a value of 12 points), and dividing this sum by the total number of credits.

    2. Remember that, in C++, when both operands in the division are integers, the result will also be an integer; the remainder will be discarded. Use “type casting”: `static_cast<type>(expression)’ to solve this problem.

  3. Verify your program by computing the GPA of a student that has two A’s and 2 B’s; what is the grade of this student, A or B (A goes from 3.5 to 4 points)? When your program is correct, save the main.cpp file and submit it using “Deliver 2” in Moodle. Remember to follow the instructions regarding the names and types of the variables, to include the names of the programmers, to document your program and to use good programming practices.