Números de 3 cifras existen cuya suma de cifras sea igual a 10 - Ejercicio [ESP-ENG] | C++

avatar
(Edited)

portada.jpg

¡Saludos Hivers! Hoy traigo un poquito más de C++, en este caso un ejercicio acerca del reto matemático diario de @ydavgonzalez ¡Les invitó a participar están geniales! Publicación del reto

En este caso se trató de responder la siguiente pregunta: ¿Cuántos números de 3 cifras existen cuya suma de cifras sea igual a 10?

Para comenzar incluí las librerías iosteam y conio para la entrada y salida de datos y para la sentencia getch, también usé el using namespace para facilitar el uso de los couts.

En la primera función salí un poco del molde solo para probar, pues aunque no responde la interrogante me sirvió de base para responderla en la siguiente función. En esta primera recibe un numero de tres cifras del usuario, lo valida de modo que se asegure que sea de tres cifras (para eso el if, else) y luego dice si la suma de sus cifras (ejemplo 331 = 3+3+1 = 7). Usé un do while para que se haga un bucle en la validación y no salga hasta que se ingrese un número de tres cifras.

Para tomar cada cifra usé el operador módulo y el de dividir, al dividir entre 10 consigo que se le quite una cifra y al usar módulo obtengo la última cifra de un número, ejemplos: 20/10 = 2, 20%10=0, 201%10=1.

Greetings Hivers! Today I bring a little bit more of C++, in this case an exercise about the daily mathematical challenge of @ydavgonzalez He invited you to participate are great! Post of the challenge

In this case it was about answering the following question: How many 3-digit numbers exist whose sum of digits is equal to 10?

To start with I included the iosteam and conio libraries for data input and output and for the getch statement, I also used the using namespace to facilitate the use of couts.

In the first function I went out a little of the mold only to test, because although it does not answer the question it served me as base to answer it in the following function. In this first one it receives a number of three digits from the user, it validates it so that it is sure that it is of three digits (for that the if, else) and then it says if the sum of its digits (example 331 = 3+3+1 = 7). I used a do while so that it loops the validation and does not exit until a three digit number is entered.

To take each digit I used the modulus operator and the divide operator, by dividing by 10 I get one digit removed and by using modulus I get the last digit of a number, examples: 20/10 = 2, 20%10=0, 201%10=1.

Programación c++.png

image.png

Habiendo entendido lo que necesitaba para responder la pregunta proseguí a hacer otra función, a la que llamé "calculator_all". Esta tiene un cout informativo y cuenta con las mismas variables que la anterior, solo que esta vez no toma información del usuario, solo le muestra un mensaje, espera que toque alguna tecla (valga la redundancia) para iniciar el for que va desde 100 hasta 999 (todos los números enteros de 3 cifras), este for se encarga de hacer las mismas ecuaciones combinando el operador módulo y el operador de división para extraer las cifras y luego almacenar su suma en la variable "r", luego, compara si esa suma es igual a 10, de ser así lo muestra en pantalla junto a un texto informativo y aumenta la variable "counter" en 1, dicha variable representa la cantidad de números que cumple la condición.

Si no se cumple la condición simplemente no realiza las operaciones anteriores y repite el proceso. Una vez finalizado el for procede a mostrar el total de números que cumplen la condición.

Finalmente está el main en el que creo dos variables para llenar los parámetros de las funciones creadas, las llamo y luego coloco el return 0.

Having understood what I needed to answer the question I proceeded to make another function, which I called "calculator_all". This one has an informative cout and has the same variables as the previous one, only this time it doesn't take information from the user, it only shows a message, it waits for him to touch some key (redundancy) to start the for that goes from 100 to 999 (all 3-digit integers), this for is in charge of doing the same equations combining the modulus operator and the division operator to extract the numbers and then to store its sum in the variable "r", then, it compares if that sum is equal to 10, if so it shows it in screen next to an informative text and it increases the variable "counter" in 1, this variable represents the quantity of numbers that fulfills the condition.

If the condition is not met, it simply does not perform the previous operations and repeats the process. Once finished the for proceeds to show the total of numbers that fulfill the condition.

Finally there is the main in which I create two variables to fill the parameters of the created functions, I call them and then I place the return 0.

image.png


Acá les dejo capturas de la ejecución del programa, una con ambas funciones y otra solo con la que realmente es relevante para la pregunta, a esta última le agregue un cout informativo que me faltó: "Presione cualquier tecla para continuar"...

Here are some screenshots of the program execution, one with both functions and the other one only with the one that is really relevant to the question, to this last one I added an informative cout that I missed: "Press any key to continue"...

image.png

image.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! Espero que les haya agradado este humilde post, 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 you liked this humble post, 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++

Calculador de edad básico 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
2 comments
avatar

Adoro los ejercicios de C++, muchas gracias por postear en la comunidad, espero ver mas post tuyos

0
0
0.000
avatar

Gracias a ustedes por crear este espacio :D

0
0
0.000