Programa multifunción (Capicúa, Perfecto o abundante, +/-) [ESP-ENG] | C++

avatar
(Edited)

Buenos días, ¿Qué tal va todo? Aquí estoy de nuevo con más programación. Solo que esta vez con C++ y no con Python.

Se me presentó un ejercicio muy interesante y lo quise compartir con ustedes. Se trata de un programa multifunción que parte del siguiente enunciado:

Realice un programa multifunciones, con los siguientes parámetros:

a - Una función que determine y muestre si el número es perfecto o abundante:

Perfecto (La suma de divisores del número es igual al *número. Y el número no debe estar incluido entre los divisores al sumarlos)

Abundante (La suma de divisores > al número)

b - Una función que muestre si un número es negativo o positivo... De ser negativo (Mostrar caracter 'N') y de ser positivo (Mostrar caracter 'P')

c - Que la función determine si el número es capicuo...

Sí es capicuo - Mostrar valor 1

No es capicuo - Mostrar valor 0

Good morning, how is everything going? Here I am again with more programming. Only this time with C++ and not with Python.

I was presented with a very interesting exercise and wanted to share it with you. It is a multifunction program that starts from the following statement:

Make a multifunction program, with the following parameters:

a - A function that determines and shows whether the number is perfect or abundant:

Perfect (The sum of divisors of the number is equal to *number. And the number must not be included between the divisors when adding them)

Abundant (The sum of divisors > to the number)

b - A function that shows if a number is negative or positive... If negative (Show character 'N') and if positive (Show character 'P')...

c - A function to determine if the number is capicuous...

If it is capicuous - Show value 1

Not capicuous - Show value 0


Portada post programacion, tech (1).gif

Programación c++.png

La primera función determina, tal y como pide el enunciado si un número es perfecto o no. Para ello calcula los divisores del número ingresado por parámetro y luego los va sumando en una variable entera a la que llamé "p". Esto en un bucle for que va desde i=1 hasta i<n, es decir desde 1 hasta 5 si se tratase de 6 por ejemplo.

Así pues, se evita que se ingrese el propio número como posible divisor. Para que ingresen solo los divisores a la suma, se filtra el iterador en un if que tiene como parámetro que el módulo de la división de n/i sea igual a 0 (división exacta).

Hay otro parámetro que realmente es redundante y es que i sea diferente de n, esto para evitar que se ingrese el propio número n como divisor. El asunto es que ya en el rango del for se está considerando que no entre dicho número. Este es un detalle del que me percaté mientras armaba este post.

Cabe destacar que i va desde 1 y no desde 0 porque de iniciar en 0, se estaría generando un error de indeterminación por división entre 0 que haría finalizar el programa.

Una vez se calcula la suma de divisores se sale del for y se entra a otro bloque condicional en el que se filtra si la suma es igual al número ingresado (caso perfecto p==n), o si la suma excede al número ingresado (caso abundante p >n), o si por otro lado no se cumplen ninguno de esos dos casos.

Posteriormente llega una función bastante clásica, la del número capicua. Esta parte de apoyarse en la operación de módulo (%), para tomar el restante de la división y de la propia división entre 10. Esto para descomponer el número ingresado. El algoritmo lo tenía guardado de mi tiempo viendo programación orientada a objetos, este es de hecho uno de los primeros ejercicios. De hecho lo había tratado antes por acá. Así que si quieres verlo explicado a detalle, da clic en el enlace.

The first function determines, as requested by the statement, if a number is perfect or not. For it calculates the divisors of the number entered by parameter and then it adds them in an integer variable to which I called "p". This in a for loop that goes from i=1 to i<n, that is to say from 1 to 5 if it were 6 for example.

This avoids entering the number itself as a possible divisor. In order to enter only the divisors to the sum, the iterator is filtered in an if that has as parameter that the modulus of the division of n/i is equal to 0 (exact division).

There is another parameter that is really redundant and it is that i is different from n, this to avoid entering the number n itself as divisor. The thing is that already in the range of the for it is considering that this number does not enter. This is a detail that I noticed while I was putting this post together.

It should be noted that i goes from 1 and not from 0 because if it starts at 0, it would generate an error of indeterminacy by division by 0 that would terminate the program.

Once the sum of divisors is calculated, we leave the for and enter another conditional block in which we filter if the sum is equal to the entered number (perfect case p==n), or if the sum exceeds the entered number (abundant case p >n), or if on the other hand none of these two cases are fulfilled.

Then comes a rather classical function, that of the capicua number. This one relies on the modulus operation (%), to take the remainder of the division and of the division by 10 itself, in order to decompose the entered number. I had the algorithm saved from my time watching object oriented programming, this is in fact one of the first exercises. In fact I had covered it here before. So if you want to see it explained in detail, click on the link.

Programación c++.png

image.png

image.png

image.png

Programación c++.png

La tercera función es la más simple, saber si un número es positivo o negativo, para esto se aplica un simple bloque ocndicional que verifique si el n ingresado es mayor que 0 (positivo), o menor que 0 (negativo). El detalle grande es que no considera el 0, que es neutro. Sin embargo, el enunciado no da pie a incluirlo.

Para finalizar, en el main declaré una variable n para recibir para recibir por teclado el número a verificar si es capicua, positivo o negativo y si es perfecto o abundante. Cabe destacar que no hay una función de validación, puesto que no se exigía. Adicionalmente añadí mensajes para facilitar la lectura de los resultados.

Dado que en el apartado de capicúa se exigía solo 0 y 1 como posible respuesta, pues el resultado es más "primitivo" por así decirlo. Y pues poco más que eso, considero que es un ejercicio muy bueno para el camino de aprendizaje.

The third function is the simplest, to know if a number is positive or negative, for this a simple ocnditional block is applied to check if the n entered is greater than 0 (positive), or less than 0 (negative). The big detail is that it does not consider 0, which is neutral. However, the statement does not allow to include it.

Finally, in the main I declared a variable n to receive by keyboard the number to verify if it is capicua, positive or negative and if it is perfect or abundant. It should be noted that there is no validation function, since it was not required. Additionally I added messages to facilitate the reading of the results.

Since in the capicua section only 0 and 1 were required as possible answers, the result is more "primitive" so to speak. And little more than that, I consider that it is a very good exercise for the learning process.

Programación c++.png

image.png

image.png

Programación c++.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

¡Y bueno, eso es todo por hoy! Este fue un ejercicio tipo parcial que se hace en papel, sin compilador ni apoyo tecnológico. Lo que le da un extra de dificultad. El enunciado me lo compartió un compañero que actualmente está cursando POO. Desde acá te envío un saludo y te agradezco por el contenido.

Existe cierta polémica por el aplicar exámenes en papel enfocado al código. Para mí es una oportunidad para retarte a ti mismo, aunque no considero que no es la forma más adecuada, pues en el mundo laboral habrá herramientas para codificar. Rara será la situación en la que solo tengas una hoja y papel, al menos es como lo veo. Sin embargo, la situación actual de la universidad es la que fuerza a que las evaluaciones presenciales sean mayormente de este tipo.

Como extra, diría que la función capicúa está bastante limitada, pues solo cubre 5 cifras. Existe otra forma de hacerlo, usando una biblioteca. Que facilita el proceso de generalización, sin embargo, en este tipo de parciales, no se acepta el uso de funciones externas.

Hay materias en las que sí se acepta dicha herramienta, pero al menos en esta, se suele ser más extricto

Well, that's all for today! This was a partial exercise that is done on paper, without compiler or technological support. Which gives it an extra difficulty. The statement, was shared with me by a colleague who is currently studying POO. From here I send you a greeting and thank you for the content.

There is some controversy about applying paper exams focused on code. For me it is an opportunity to challenge yourself, although I do not consider that it is not the most appropriate way, because in the working world there will be tools for coding. Rare will be the situation where you only have a sheet and paper, at least that's how I see it. However, the current university situation is what forces face-to-face evaluations to be mostly of this type.

As a bonus, I would say that the capicua function is quite limited, as it only covers 5 digits. There is another way to do it, using a library. That facilitates the generalization process, however, in this type of midterm, the use of external functions is not accepted.

There are subjects in which such a tool is accepted, but at least in this one, it is usually more strict.

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

Realmente te felicito por seguir aportando tus conocimientos con respecto a la programación, y lo que adquieres día a día en tu campo de estudio. Éxitos @gabrielr29

!PIZZA

0
0
0.000
avatar

¡Muchas gracias por sus felicitaciones! Aprecio su constante apoyo :D

0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000
avatar

topzeira sempre quis programar,bom trbalho garotao 😎
!PIZZA

0
0
0.000