Calculador de edad básico [ESP-ENG] | C++

avatar
(Edited)


portada.JPG

¡Buenas! Hoy les traigo un poco de programación. Se trata de un ejercicio que le asignaron a un compañero de la universidad que está un poco atrás en esta rama por causa de que viene de un cambio de carrera.

Me pidió apoyo porque se sentía un poco bloqueado por lo que le tendí la mano para que comprendiera como resolver este tipo de asignaciones. El enunciado iba algo así "Realice un programa que calcule la edad tomando el mes y el año que ingrese el usuario, sin tomar en cuenta el día, no se permiten sentencias repetitivas".

Hello! Today I bring you a little bit of programming. This is an exercise that was assigned to a college classmate who is a little behind in this branch because he comes from a career change.

He asked me for support because he felt a little blocked so I reached out to him to help him understand how to solve this type of assignment. The statement went something like this "Make a program that calculates the age taking the month and year entered by the user, without taking into account the day, repetitive sentences are not allowed".

Programación c++.png

Comencé incluyendo las librerías necesarias para la entrada y salida de datos, el uso del "getch" para evitar que el programa se cierre de golpe y finalmente el "using namespace std" para facilitar el uso del "cout".

I started by including the necessary libraries for data input and output, the use of "getch" to prevent the program from slamming and finally the "using namespace std" to facilitate the use of "cout".


image.png

Luego continué creando una función a la que llamé "funcion_data" con los parámetros "m y a" para el mes y año que ingresará el usuario, "edad" para tomar la edad calculada, "a_actual y m_actual" para asignar el año y mes actual de referencia. Estas últimas dos podrían tomarse del sistema pero dado que es un programa básico y tiene limitaciones en el enunciado, pensé que no sería prudente agregar ese tipo de funciones. Dentro de "funcion_data" coloqué un cout y cin para avisar al usuario que dato ingresar y luego tomarlo, en este caso el mes. Posteriormente un if para condicionar que el mes no pase de 12 ni sea menor a 1, en caso de cumplirse la condición manda un mensaje de error y luego se cierra el programa, por causa de que no se permite usar sentencias repetitivas, según el enunciado del ejercicio.

El siguiente cout y cin se encarga del año y está dentro del "else" de modo que solo se ejecute si no se cumple la condición. Una vez se recopila la data, se verifica por medio de otro if, else, en el que marca un rango de 120 años máximo, evitando el 2021/año actual pues resultaría en 0 años. Usé la palabra "year" en vez de "año" porque en inglés no está presente la "ñ" y la palabra resultante es "ano", curiosidad graciosa pero quizás para el profesor no tanto, esto depende de tu "suerte", supongo jajaja.

Si no se cumple la condición se entra a una ecuación simple en la que se calcula la edad restando el año actual con el año ingresado y luego se comprueba si el mes actual es menor que el mes ingresado, en caso tal se resta un año a la edad antes calculada. En caso contrario entra en un else vacío, es decir no hay cambios en la edad. Finalmente se muestra la edad calculada.

I then went on to create a function which I called "function_data" with the parameters "m and a" for the month and year to be entered by the user, "age" to take the calculated age, "a_current and m_current" to assign the current reference year and month. These last two could be taken from the system but since it is a basic program and has limitations in the statement, I thought it would not be wise to add that kind of functions. Inside "funcion_data" I placed a cout and cin to let the user know what data to enter and then take it, in this case the month. Later an if to condition that the month does not exceed 12 or is less than 1, in case the condition is fulfilled it sends an error message and then the program closes, because it is not allowed to use repetitive sentences, according to the statement of the exercise.

The following cout and cin is in charge of the year and is inside the "else" so that it is only executed if the condition is not fulfilled. Once the data is collected, it is verified by means of another if, else, in which it marks a range of 120 years maximum, avoiding the 2021/current year because it would result in 0 years. I used the word "year" instead of "año" because in English the "ñ" is not present and the resulting word is "ano", funny curiosity but maybe for the teacher not so much, this depends on your "luck", I guess hahaha.

If the condition is not met, a simple equation is entered in which the age is calculated by subtracting the current year with the year entered and then it is checked if the current month is less than the month entered, if so, a year is subtracted from the age calculated before. Otherwise it enters an empty else, i.e. there is no change in age. Finally the calculated age is displayed.

image.png

image.png

Programación c++.png

image.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! Espero que esta calculadora de edad básica pueda ser de ayuda para algún estudiante universitario u algún autodidacta que ande por estos lares de la red, o quizás sea alguien que esté realizando una búsqueda bien salvaje y termine por acá, saludos desde el 2021 por si es el caso, estoy seguro de que si ya eres hasta del 2050 el socialismo sigue sin funcionar.

Si te interesa otro tutorial de programación acá te dejo los links a los que he realizado hasta ahora:

And well... That's all for today! I hope this basic age calculator can be of help to some college student or some autodidact who is around these parts of the network, or maybe it is someone who is doing a wild search and ends up here, greetings from 2021 in case it is the case, I'm sure that if you are already up to 2050 socialism still does not work.

If you are interested in another programming tutorial here are the links to the ones I have done until now:


Calculador de datos para un triángulo rectángulo en C++

Concecionario de autos, ejercicio en JAVA

Programación c++.png

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

Diseño sin título.gif

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



0
0
0.000
3 comments
avatar

Holaaa @gabrielr29 me hiciste recordar mis tiempos de estudio 🤭. También me hizo reflexionar que necesito volver a repasar todo lo que vi jajajaja he olvidado muchas cosas. Definitivamente es importante siempre estar constantemente estudiando. Creo que a veces lo ajetreado de la vida te hace olvidar muchas cosas importantes. No dejes nunca que eso te pase, ejercita constantemente tu mente y busca siempre adquirir o recordar lo visto . Se nota que eres muy inteligente sigue así. Bendiciones ✨.

0
0
0.000
avatar

Graciaaas, me alegra que la nostalgia te haya visitado un rato por haber leído este humilde postcito, muchas bendiciones para ti también, tomaré muy en cuenta tu consejo :D

0
0
0.000