Calculadora de suma y resta de matrices ¡Practicando con AzulSchool! [ESP-ENG] | C++

avatar
(Edited)

¿Cómo va todo? Por acá estoy de vuelta con... ¡Más C++! De la mano del curso gratuito de AzulSchool, creado por Angel Sánchez. Actualmente llevo un 60% completado, tuve un bajón en cuanto al tiempo que le dedicaba por una serie de trabajos que tuve que atender. Esto me pasó fuerte factura pues me quedan 9 días para lograr la meta, el reto no es tan duro considerando que solo es un 40% pero igual no debe subestimarse. Para el proyecto de hoy, se pide crear un calculadora que permita sumar y restar matrices, procedimiento sencillo que recuerdo haber visto en bachillerato y también en la universidad pero junto a otras operaciones de mayor dificultad que requerían el apelar a teoremas, pero eso podría ser para otra publicación. El paso a paso para realizar la operación de suma o resta correctamente, es explicado en el enunciado.

How is everything going? I'm back with... More C++! From the free AzulSchool course, created by Angel Sanchez. I'm currently 60% complete, I had a downturn in terms of the time I dedicated to it due to a series of jobs I had to attend. This took a heavy toll on me because I have 9 days left to achieve the goal, the challenge is not so hard considering that it is only 40% but still should not be underestimated. For today's project, I am asked to create a calculator that allows to add and subtract matrices, a simple procedure that I remember having seen in high school and also in college but along with other more difficult operations that required appealing to theorems, but that could be for another publication. The step-by-step to perform the addition or subtraction operation correctly is explained in the statement.


Portada post programacion, tech.png
Edited with CANVA

Programación c++.png

image.png
From AzulSchool, by: Angel Sánchez

Programación c++.png

Para empezar no hubo mucha variación con respecto a las librerías que usé, también me apoyé en varias funciones que he traído antes, para verificar la entrada por teclado correctamente. En el main solo llame a la función principal, "Matrix_menu()" que en breve explicaré. La primera función que se encuentra al bajar es "ToString", que no es más que un selector que dependiendo del numero que reciba, devuelve el mismo numero pero ya no como un "int" sino como un "string", de ahí el nombre de la función.

La creé para que el mensaje que se muestra con las coordenadas de la matrix al ser rellenada, pudiese ser armado sin problemas, esto lo veremos pronto, al llegar al comprobador. La función "comprobador" ha sido recurrente por estos lados, pues en la gran mayoría de los casos es necesario verificar que el usuario ingrese el tipo de datos correctos por teclado. Sin embargo, en esta ocasión hice varias modificaciones, pues para el caso anterior había que incluir un rango (mínimo-máximo), que requería el enunciado, sin embargo en este caso solo coloqué un máximo y las coordenadas i-j que estarán asociadas al ciclo for, esto para mostrar las coordenadas en las que estará ubicado el dato que el usuario añada a la matriz. Se le coloca "i+1"/"j+1" para que sea más comprensible para el usuario, pues debemos recordar que la matriz empieza en la posición "0" y no "1". Además de ese cambio, también es evidente que ya no se encarga unicamente de filtrar datos de tipo "int", sino que ha migrado al tipo "float", por ello el tipo de dato de la función es ahora "float", la conversión se hace con "stof" y ya no uso la función "IsNumberInt" sino "IsFloat", que expliqué en el anterior proyecto, tomada de StackOverFlow para hacer correctamente la validación, gracias nuevamente al usuario "eferion" por dejar a disposición ese método bien resumido para validar. El resto de la función no varía respecto a sus anteriores apariciones en el blog.

To begin with there was not much variation with respect to the libraries I used, I also relied on several functions that I have brought before, to verify the keyboard input correctly. In the main just call the main function, "Matrix_menu()" which I will explain shortly. The first function you find when you go down is "ToString", which is nothing more than a selector that depending on the number it receives, returns the same number but no longer as an "int" but as a "string", hence the name of the function.

I created it so that the message that is shown with the coordinates of the matrix when it is filled, could be assembled without problems, this we will see soon, when arriving at the tester. The function "tester" has been recurrent around these parts, because in most of the cases it is necessary to verify that the user enters the correct type of data by keyboard. However, in this occasion I made several modifications, because for the previous case it was necessary to include a range (minimum-maximum), that required the statement, nevertheless in this case I only placed a maximum and the coordinates i-j that will be associated to the cycle for, this to show the coordinates in which will be located the data that the user adds to the matrix. It is placed "i+1"/"j+1" to make it more understandable for the user, because we must remember that the matrix starts at position "0" and not "1". In addition to this change, it is also evident that it is no longer responsible only for filtering data of type "int", but has migrated to the type "float", so the data type of the function is now "float", the conversion is done with "stof" and no longer use the function "IsNumberInt" but "IsFloat", which I explained in the previous project, taken from StackOverFlow to make the validation correctly, thanks again to the user "eferion" for making available this well summarized method to validate. The rest of the function is unchanged from its previous appearances in the blog.

Programación c++.png

image.png

image.png

image.png

image.png

image.png

IsFloat - From StackOverFlow

Programación c++.png

Para la función principal "M_Calculator", declaré una variable de tipo float y tres arreglos bidimensionales o matrices de tipo float también. Los parámetros son "int d" para las dimensiones elegidas y "char operation" para saber si quiere sumar o restar. Luego de esto siguen dos dobles-for que se encargan del filtrado y rellenado de cada matriz, apoyándose en la función de "Float_comprobator(max,i,j)", el propio validador ayuda mostrando las coordenadas como mencioné antes, por ello se incluyen las coordenadas en los parámetros. Luego de incluir el valor, se limpia el buffer, el segundo for es un gemelo del primero solo que rellena la segunda matriz, quería hacer una función que me ayudara a no redundar en código pero se me complicó un poco el asunto al incluir una matriz en los parámetros, así que por esa parte el asunto está un poco mal optimizada. Luego del rellenado de las matrices viene un if-else que según el operador "+" o "-", incluido en los propios parámetros de la función, en caso "+" se suman ambas matrices y se rellenan los valores obtenidos dentro de la matriz mr (cuyo nombre significa matriz resultante), a través de un doble for. En caso "-" pues se resta de la misma manera. Luego de eso se muestra la matriz resultante con un doble for, también se muestran las matrices ingresadas de la misma forma, como vemos esos bucles se repiten bastante.

La función "S_or_R()", es un simple selector que devuelve "+" o "-" según elija el usuario, esto para complementar la función explicada anteriormente. Luego en el menú principal notamos un selector que muestra las dimensiones posibles a operar, para cada opción se llama a la función "M_Calculator" con la dimensión y la función "S_or_r()" para el segundo parámetro, que llamara al selector para que el usuario elija cual operación desea realizar. Esta función es de hecho bastante parecida a los menús que he mostrado antes, todas parten de una misma plantilla.

For the main function "M_Calculator", I declared a variable of type float and three two-dimensional arrays or matrices of type float as well. The parameters are "int d" for the chosen dimensions and "char operation" to know if you want to add or subtract. After this follows two double-for's that take care of the filtering and filling of each array, relying on the "Float_comprobator(max,i,j)" function, the validator itself helps by showing the coordinates as I mentioned before, that's why the coordinates are included in the parameters. After including the value, the buffer is cleaned, the second for is a twin of the first one only that fills the second matrix, I wanted to make a function that would help me to not redundant code but I got a little complicated by including an array in the parameters, so for that part the issue is a little poorly optimized. After the filling of the matrices comes an if-else that according to the operator "+" or "-", included in the parameters of the function, in case of "+" both matrices are added and the values obtained are filled inside the matrix mr (whose name means resulting matrix), through a double for. In case of "-", we subtract in the same way. After that the resulting matrix is shown with a double for, also the entered matrices are shown in the same way, as we can see these loops are quite repeated.

The function "S_or_R()", is a simple selector that returns "+" or "-" according to the user's choice, this to complement the function explained above. Then in the main menu we notice a selector that shows the possible dimensions to operate, for each option the function "M_Calculator" is called with the dimension and the function "S_or_r()" for the second parameter, which will call the selector for the user to choose which operation to perform. This function is in fact quite similar to the menus I have shown before, they all start from the same template.

Programación c++.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

record_000026.gif

Created with VSDC Free Video Editor and Img2Go

image.png

image.png

image.png

image.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! En total son 9 proyectos, he traído 4/9, falta poco, espero darle fuerte esta semana y traer todos si es posible.

And well... That's all for today! In total there are 9 projects, I have brought 4/9, I hope to bring them all this week and bring them all if possible.

Programación c++.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
9 comments
avatar

Interesante el curso y por supuesto el programa, las matrices son herramientas muy importantes que muchas personas desconocen de su utilidad por la misma dependencia de los dispositivos y computadoras

0
0
0.000
avatar

Sí, tantas facilidades nos han embrutecido en cierta medida

untitled.gif

0
0
0.000
avatar

hola, señorito devolviéndote el cariño.
para serte sincera al leer no entiendo nada soy mas de practica.
pero si me gustaba las matemáticas hasta que deje de estudiar y olvide todo xd.

te felicito por mantener la mente ocupada en esta linda materia.
un placer compartir contigo y ayudar a @kat-nee para que la actividad sea posible.
comentario y apoyo 5.
feliz dia.

0
0
0.000
avatar

¡Gracias por el apoyo! Feliz día para usted también :D

untitled.gif

0
0
0.000
avatar

Hola Gabriel que bueno que mantengas tu mente ocupada y que ese curso que hiciste, esa aplicación te sirva como herramienta para ayudar a otras personas que presentan dificultades con los números, a simple vista todo muy fácil.

0
0
0.000