Calculadora básica con funciones ¡Último proyecto del curso de AzulSchool! | C++

avatar
(Edited)

¡Saludos! Hoy estoy por acá para compartirles no solo la última publicación de esta serie correspondiente a los proyectos de C++ asignados en el curso profesional de C++ creado por Ángel Sánchez en AzulSchool, sino también un logro que hace ya bastante que quería alcanzar. Al fin culminé todo el material correspondiente al curso y tengo mi certificado.

Luego de este proyecto seguía el módulo de punteros, el cual contaba con un ejercicio personalizado opcional que decidí no incluir en esta serie, pues considero que hasta este noveno proyecto les habré compartido suficiente respecto al contenido impartido y también sobre mis experiencias.

Este proyecto se enfoca en el uso de funciones, aunque lo cierto es que las vengo usando desde hace tiempo para validar dentro de lo posible, evitar el código repetido y ampliar el alcance de la propia práctica al irme adecuando a un tipo de programación un poco más optimizada, aunque aun me falta bastante.

La calculadora debe ser capaz de sumar, restar, aplicar potenciación, dividir, sacar raíz cuadrada y multiplicar. Dado que en cuanto a raíz no especifica si se debe incluir una aparte de la cuadrada, decidí solo incluir esa. Para las funciones las cosas fueron bastante simples, pues a través del retorno de cada una se aplica la operación que indica su nombre, "Sum" para sumar dos números, "Subtract" para restar, "Multiplication" para multiplicar y así sucecivamente. En el caso de la potencia incluí el parámetro "n" para cumplir con el enunciado en cuanto a "elevar a cualquier potencia", esto a través de la función pow. En el caso de "Square_root" pues se aplica para las raíces cuadradas, por medio de la función sqrt, facilitada por la librería "math.h".

Greetings! Today I'm here to share with you not only the last post of this series corresponding to the C++ projects assigned in the professional C++ course created by Angel Sanchez at AzulSchool, but also an achievement that I wanted to reach a long time ago. I finally finished all the material corresponding to the course and I have my certificate.

After this project followed the pointers module, which had an optional custom exercise that I decided not to include in this series, because I consider that until this ninth project I will have shared enough about the content taught and also about my experiences.

This project focuses on the use of functions, although the truth is that I have been using them for some time to validate as much as possible, avoid repeated code and expand the scope of the practice itself by adapting to a type of programming a little more optimized, although I still have a long way to go.

The calculator must be able to add, subtract, apply power, divide, take square root and multiply. Since it does not specify whether to include a root other than the square root, I decided to include only that one. For the functions things were quite simple, since through the return of each one the operation that its name indicates is applied, "Sum" to add two numbers, "Subtract" to subtract, "Multiplication" to multiply and so on. In the case of power I included the parameter "n" to comply with the statement regarding "raise to any power", this through the pow function. In the case of "Square_root" it is applied for square roots, through the sqrt function, provided by the "math.h" library.


Portada post programacion, tech.jpg

Edited with CANVA

Programación c++.png

image.png

image.png

image.png

Programación c++.png

El reciclaje también estuvo presente aquí pues "interfaz_Colect" estuvo de vuelta para cumplir la función de siempre, al ser una plantilla de mensaje informativo. "Show_R" fue una plantilla para mostrar los resultados con una reducción en los decimales, de modo que se facilite la lectura.

"number_colector(string a)", fue la función que cree para filtrar los números recibidos por teclados, de modo que no se permiten letras ni caracteres especiales, la validación parte del código que comenté en el anterior proyecto, esa porción del try-catch no es mía, sino que la tomé de un foro que explica las formas posibles de conversión de cadenas de caracteres a enteros, solo la adapte para valores flotantes.

Recycling was also present here as "interface_Colect" was back to fulfill its usual function, being an informative message template. "Show_R" was a template to display the results with a reduction in decimals, so as to make it easier to read.

"number_collector(string a)", was the function I created to filter the numbers received by keyboards, so that no letters or special characters are allowed, the validation part of the code I commented in the previous project, that portion of the try-catch is not mine, but I took it from a forum that explains the possible ways to convert strings to integers, I only adapted it for floating values.

Programación c++.png

image.png

image.png

Programación c++.png

Llega finalmente el menú, en donde reciclé la plantilla de siempre pero adapte la recolección de los números por teclado a las funciones creadas, de tal manera que se usan dos strings con la función "number_colector", que a su vez usa "interfaz_Colect" para dar el mensaje personalizado y aplicar la validación a los datos que se reciban. Una vez se validan los números, se usa la función "Show_R" con la función "Sum" en su parámetro para que muestre el resultado obtenido, aplicándole cout.precision(2), de modo que los decimales no sean demasiados.

Con la resta se aplica el mismo procedimiento, a excepción de que se usa la función "Subtract" dentro de "Show_R". Para la multiplicación nuevamente se sigue la misma linealidad pero para la división se aplica una validación, pues hay que evitar las divisiones entre 0. Para este apartado aplique un if-else.

Ya en la potencia, cambian los mensajes por cuanto un número será la base y el otro el exponente. Finalmente, la opción 6 que corresponde a las raíces cuadradas, posee una validación que corresponde a los números menores a 0, pues las raíces de números negativos se trabajan con números imaginarios, apartado que no se contempla en esta calculadora simple.

En esencia eso es todo el código, sin embargo, resaltaría que esta calculadora simple tiene como desventaja que para la resta, suma, multiplicación y división no hay continuidad respecto al resultado, es decir, no puedes seguir operando con el mismo como en una calculadora de oficina, por ejemplo. Esto se puede resolver con algunos bucles, sin embargo, no opté por darle más tiempo a este proyecto porque quiero continuar con otras metas y ya hasta aquí cumple con lo requerido y un poco más.

Finally the menu arrives, where I recycled the usual template but I adapted the collection of the numbers by keyboard to the created functions, in such a way that two strings are used with the function "number_collector", which in turn uses "interface_Collect" to give the customized message and to apply the validation to the received data. Once the numbers are validated, the function "Show_R" is used with the function "Sum" in its parameter to show the result obtained, applying cout.precision(2), so that the decimals are not too many.

With the subtraction the same procedure is applied, except that the function "Subtract" is used inside "Show_R". For the multiplication again the same linearity is followed, but for the division a validation is applied, because it is necessary to avoid divisions between 0.

For the power, the messages change because one number will be the base and the other the exponent. Finally, the option 6 that corresponds to the square roots, has a validation that corresponds to the numbers smaller than 0, because the roots of negative numbers are worked with imaginary numbers, section that is not contemplated in this simple calculator.

In essence that is all the code, however, I would emphasize that this simple calculator has the disadvantage that for subtraction, addition, multiplication and division there is no continuity with respect to the result, ie, you can not continue operating with the same as in an office calculator, for example. This can be solved with some loops, however, I did not choose to give more time to this project because I want to continue with other goals and so far it fulfills what is required and a little more.

Programación c++.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

record_000065.gif

Programación c++.png

¡Y bueno... Eso es todo por hoy y por este curso de C++ profesional de AzulSchool! Espero que haya sido de provecho el contenido que traje al respecto, gracias por tomarte el tiempo de leer hasta acá. El certificado que asignan tiene un identificador único que permite verificarlo, de modo que si decides emprender también este viaje, te aseguro que valdrá la pena y tendrás como darle validez a nivel laboral.

Tan solo añadiría que algunos videos se me hicieron pesados por la forma en la que se planteo el tema, pero no fue nada grave, la gran mayoría fueron bastante didácticos. La posibilidad de pedir apoyo en el foro o consultar avances de anteriores estudiantes me parece genial, si te atascas en algún detalle puedes encontrar ayuda a través de ese medio. Para mi lo más difícil fue la constancia, pues comencé en julio del 2020, me detuve y seguí en octubre de ese año para luego terminar en un parón hasta septiembre del presente año 2022, luego el ritmo bajó bastante por la universidad y lo terminé el 02/12/2022. Lento pero seguro como decía mi abuelo, aunque lo cierto es que debo ser más diligente en próximos cursos.

And well... That's all for today and for this AzulSchool professional C++ course! I hope you found the content I brought about it useful, thank you for taking the time to read this far. The certificate they assign has a unique identifier that allows you to verify it, so if you decide to undertake this journey as well, I assure you that it will be worth it and you will be able to validate it for work purposes.

I would only add that some of the videos were a bit heavy due to the way in which the subject was presented, but it was nothing serious, most of them were quite didactic. The possibility of asking for support in the forum or consulting the progress of previous students is great, if you get stuck in some detail you can find help through that medium. For me the most difficult thing was the constancy, because I started in July 2020, I stopped and continued in October of that year and then finished in a hiatus until September of this year 2022, then the pace slowed down quite a bit because of the university and I finished it on 02/12/2022. Slow but sure as my grandfather used to say, although the truth is that I must be more diligent in future courses.


¡Cómo regalo extra, subí el código de todos los proyectos a github! Puedes acceder acá debajo:


As an extra gift, I uploaded the code of all the projects to github! You can access it here below:


https://github.com/gabrielr29/Curso-profesional-de-C-AzulSchool


image.png

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
5 comments
avatar

Es un resumen informativo del contenido que te gusta y dominas. Escribes con pasión sobre el curso que deseabas terminar con éxito. No entiendo, pero lo que importa es que tu grupo y la comunidad te comprendan.

Abrazos!

0
0
0.000
avatar

Gracias por tan gratas palabras, bendiciones!

0
0
0.000
avatar

Me gusto mucho tu post y veo que aprendiste más sobre este tema en tu curso.. te felicito

0
0
0.000
avatar

Thank you so much for your support of my @v4vapp proposals in the past, my previous one expired this week.

I'd be really happy if you would continue supporting my work by voting on this proposal for the next 6 months:

Additionally you can also help this work with a vote for Brianoflondon's Witness using KeyChain or HiveSigner

If you have used v4v.app I'd really like to hear your feedback, and if you haven't I'd be happy to hear why or whether there are other things you want it to do.

0
0
0.000