Serie Fibonacci [ESP-ENG] | C++

avatar
(Edited)

Portada.jpg

¡Buen día! Por acá traigo más sobre programación. Esta vez se trata de un ejercicio más simple que el anterior: Crear un programa capaz de generar una sucesión de Fibonacci. Esta serie matemática empieza con 0 y 1, luego va creciendo a partir de la suma de los 2 números anteriores, es decir 0,1,1,2,3,5 (...)

Good morning! Here I bring more about programming. This time it is a simpler exercise than the previous one: Create a program capable of generating a Fibonacci sequence. This mathematical series starts with 0 and 1, then it grows from the sum of the 2 previous numbers, that is 0,1,1,2,3,5 (...)

Programación c++.png

Para empezar usé las librerías de siempre, "iostream" para entrada y salida de datos, "conio.h" para las pausas y captura de datos inmediatos por teclado a través de la función getch(). Y "windows.h" para la limpieza de pantalla.

Luego reciclé la función "selector" que es la misma que tiendo a usar para los selectores en muchos de mis programas. Un error dentro de ella en esta ocasión fue que no borré dos variables que usé antes pero que acá no hacen falta. Estas son "numberint" y "numberdiv".

Dentro del selector se encuentra el mensaje de bienvenida y luego un bucle while que involucra el selector principal para empezar o finalizar el programa al ejecutarlo. En el caso "1" que es para iniciarlo se inicia un do-while que incluye un cout.presicion para evitar los decimales y luego un cout que muestra las dos variables que son base para el avance de la sucesión. Estas variables son n1 y n2.

Una vez se muestran en pantalla proceden a actualizar su valor a partir de las dos ecuaciones que están debajo. Usé un While y no un Do-While en el bucle principal para que funcionara correctamente la segunda opción, es decir si quiere continuar la serie o ya está satisfecho con el intervalo mostrado. En caso de querer continuar el bucle se reinicia la variable "contador" de modo que el do-while se repita, pero no se reinician las variables n1 y n2 para que la sucesión no vuelva desde el principio.

To start I used the usual libraries, "iostream" for data input and output, "conio.h" for the pauses and immediate data capture by keyboard through the getch() function. And "windows.h" for screen cleaning.

I then recycled the "selector" function which is the same one I tend to use for selectors in many of my programs. A mistake inside it this time was that I did not delete two variables that I used before but that are not needed here. These are "numberint" and "numberdiv".

Inside the selector is the welcome message and then a while loop that involves the main selector to start or end the program when executing it. In case "1", which is to start it, a do-while loop is started that includes a cout.presicion to avoid decimals and then a cout that shows the two variables that are the basis for the progress of the sequence. These variables are n1 and n2.

Once they are displayed on screen they proceed to update their value from the two equations below. I used a While and not a Do-While in the main loop so that the second option would work correctly, that is, if you want to continue the series or if you are already satisfied with the interval shown. In case you want to continue the loop you reset the variable "counter" so that the do-while repeats, but you do not reset the variables n1 and n2 so that the sequence does not return from the beginning.

image.png

image.png

Programación c++.png

En caso de querer finalizar el bucle se muestra un mensaje en pantalla, se asigna el "0" a la variable "opc" que está vinculada al bucle principal para que así finalice el programa.

Un detalle a mejorar en el futuro sería que las variables tipo "double" tienen un límite por lo que si no se limitan el número de veces posibles que el usuario puede continuar la sucesión, llegará un punto en el que ya no será posible mostrar un número tan grande por no poder ser almacenado. Lo que hará que solo se muestre la palabra "inf".

In case you want to end the loop, a message is displayed on the screen, "0" is assigned to the variable "opc" which is linked to the main loop so that the program ends.

A detail to improve in the future would be that the variables type "double" have a limit so that if the number of possible times that the user can continue the sequence is not limited, there will come a point in which it will no longer be possible to show such a large number because it cannot be stored. This will cause only the word "inf" to be displayed.

image.png

image.png

Programación c++.png

image.png

image.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! Espero que este programita pueda ser de ayuda para tu proceso de aprendizaje o proyectos personales. Ya llegamos a 31 publicaciones sobre programación, espero, si Dios permite, algún día llegar a 100 y que este conocimiento beneficie a muchos!

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 little program can be helpful for your learning process or personal projects. We have already reached 31 publications on programming, I hope, God willing, that someday we will reach 100 and that this knowledge will benefit many!

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


Título/TittleLINKTítulo/TittleLINK
Calculador de datos para un triángulo rectángulo en C++1Graficando números en consola (0-3) C++16
Concecionario de autos, ejercicio en JAVA2Graficando números en consola II (4-6) C++17
Calculador de edad básico C++3Graficando números en consola III (7-9) C++18
Inversor de números de tres cifras4Calculadora de ecuaciones cuadráticas C++19
¿Cuántos números de 3 cifras existen cuya suma sea 10? - ¡Respondiendo a otro usuario! C++5Dados digitales C++20
Calculadora simple, cifra menos significativa y portada simple C++6Fichas biográficas de próceres C++21
¡Vistazo a BeatUDO! JAVA7Calculadora de divisores C++22
Comprobar si un número de dos cifras es primo C++8Calculadora de divisores II C++23
Conversor de pulgadas a 7 unidades distintas C++9Graficando letras en consola I (ABCDE) C++24
Comprobar si un número es capicúa (Máx 5 cifras) C++10Graficando letras en consola II (FGHIJ) C++25
Comprobador de caracteres C++11Graficando letras en consola III (KLMNO) C++26
Calculadora de índice de masa corporal C++12Graficando letras en consola V (UVWXYZ) C++27
Calculadora de factoriales C++13Generador de letras aleatorias C++28
Conversor (Grados Celsius - Fahrenheit - Kelvin) C++14Verificador de generación C++29
Calculadora de longitud, diametro y área de una circunferencia C++15¿Dados otra vez? Craps!30

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

Gracias @gabrielr29 por participar en la actividad Curaciones Matutinas, ¡Feliz día!

0
0
0.000
avatar

Vaya, es interesante, demasiado interesante, excelente información Joven

0
0
0.000