Calculadora de Perimetros y Áreas de una Circunferencia | C++

avatar

Saludos, por acá vuelvo con un poco de programación, esta vez el programa es mucho más sencillo en comparación con los últimos que había traído, esto en parte porque quería bajar un poco la intensidad en pro a administrar el tiempo disponible. El enunciado es: "Escriba un programa que reciba como entrada el radio de un círculo y entregue como salida su perímetro y su área". Forma parte de un conjunto de ejercicios de la materia "Taller de Programación Orientada a Objetos", este es uno de los primeros asignados, por ello no se ve el paradigma POO.

Greetings, here I come back with a little programming, this time the program is much simpler compared to the last ones I had brought, this partly because I wanted to lower the intensity a little in order to manage the time available. The statement is: "Write a program that receives as input the radius of a circle and gives as output its perimeter and area". It is part of a set of exercises of the subject "Object Oriented Programming Workshop", this is one of the first ones assigned, that is why the OOP paradigm is not seen.


Portadas para los post de programación - Plantilla Modelo2.jpg

Programación c++.png

Las librerias corresponden a varias ya bastante conocidas, "iostream" para la entrada y salida por teclado, "conio.h" para los getch(), "windows.h" para las limpiezas de pantalla, "cstdlib" para la función fflush y "math.h" quedó en desuso porque prioricé reducir bastante las líneas de código por lo que no usé pow() para elevar, aunque sé que podría haber usado la variable PI que trae, no recuerdo exactamente la forma de llamarla con "math.h" así que decidí simplemente crear una variable universal pi y así ahorrar algo de tiempo.

La primera función "perim(double radio)", se encarga de calcular el perimetro de un circulo a partir de su radio. La variable de tipo double "p" almacena el resultado de la multiplicación de pi por el radio y a su vez por 2, para posteriormente retornarlo.

La segunda función se encarga de calcular el area a partir del radio recibido por teclado. Para ello usa la formula pi*(radio^2), dado que la potencia es de 2, simplemente multipliqué el radio por si mismo y así evité usar la función pow. Este truco es algo viejo y si no recuerdo mal lo había hecho antes por acá, un profesor me lo mostró mientras me sugería reducir bastante la cantidad de código que empleaba en mis programas.

La tercera función es un selector, bastante común en mi blog, pues la uso bastante en mis programas. Tan solo la adapto según sea necesario en cada situación. El selector tiene la variable "opc" para la elección en el switch y la variable "radio" para almacenar el radio proporcionado por el usuario. Luego está el bucle do-while que permite que se repita la ejecución si el usuario quiere calcular más de un perímetro. Dentro de los cout usé "\t" para el espaciado, también añadí un recuadro para darle algo de estética y sus respetivos saltos de línea.

Una vez se recoge el radio, se muestra por pantalla el perímetro y el área, llamando las funciones correspondientes antes mencionadas. Posteriormente se usa "fflush" para limpiar la entrada por teclado y así evitar posibles errores de lectura. Las opciones del switch contemplan el continuar si se pulsa cualquier tecla (default) o salir si se pulsa (0). Siendo objetivos "0" cumpliría con "cualquier tecla" por lo que sería prudente corregir ese texto informativo por si desea salir pulse "0", de lo contrario pulse cualquier otra tecla.

The libraries correspond to several well known ones, "iostream" for keyboard input and output, "conio.h" for the getch(), "windows.h" for the screen wipes, "cstdlib" for the fflush function and "math. h" was left in disuse because I prioritized to reduce the lines of code so I did not use pow() to raise, although I know I could have used the PI variable that comes with it, I do not remember exactly how to call it with "math.h" so I decided to simply create a universal variable pi and thus save some time.

The first function "perim(double radius)", is in charge of calculating the perimeter of a circle from its radius. The variable of type double "p" stores the result of the multiplication of pi by the radius and in turn by 2, to later return it.

The second function is in charge of calculating the area from the radius received by keyboard. For this it uses the formula pi*(radius^2), since the power is 2, I simply multiplied the radius by itself and thus avoided using the pow function. This trick is something old and if I remember correctly I had done it before, a professor showed it to me while he suggested me to reduce the amount of code that I used in my programs.

The third function is a selector, quite common in my blog, because I use it a lot in my programs. I just adapt it as needed in each situation. The selector has the variable "opc" for the choice in the switch and the variable "radius" to store the radius provided by the user. Then there is the do-while loop that allows the execution to repeat if the user wants to calculate more than one perimeter. Inside the cout I used "\t" for the spacing, I also added a box to give it some aesthetics and its respective line breaks.

Once the radius is collected, the perimeter and area are displayed on the screen, calling the corresponding functions mentioned above. Subsequently, "fflush" is used to clear the keyboard input to avoid possible reading errors. The switch options contemplate to continue if any key is pressed (default) or exit if pressed (0). Being "0" a target would comply with "any key" so it would be prudent to correct this informative text so that if you wish to exit press "0", otherwise press any other key.

Programación c++.png

image.png

image.png

image.png

Programación c++.png

Una vez hice las pruebas, busqué también una calculadora en línea para comprobar. El sitio se llama "calculat.org". Cabe destacar que no hay validaciones por lo que una mala entrada por teclado distinta de un número entero o flotante, podría provocar errores.

Once I did the tests, I also looked for an online calculator to check. The site is called "calculat.org". It should be noted that there are no validations so a bad keyboard entry other than an integer or float, could cause errors.

image.png

image.png

image.png

image.png

image.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! Espero que esta calculadora de perímetros y áreas de círculos sea de bendición en tus estudios personales. Puedes encontrar más ejercicios de programación en mi blog, espero pronto hacer una página paralela donde ordenarlos porque ya pasan los 30 y podría tener problemas de spam si añado repetidamente ese mismo texto.

And well... That's all for today! I hope this perimeters and areas of circles calculator will be a blessing in your personal studies. You can find more programming exercises in my blog, I hope soon to make a parallel page where to order them because they are past 30 and I could have spam problems if I repeatedly add that same text.

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

Whoever is directly controlling the V2K told me to kill myself.
They told me if I killed myself now it would save the lives of countless others.
Saying the longer I wait to kill myself the more people will suffer.


They are reckless and should have shown the proper media what they had before taking me hostage for 5 years. I know there are many in prison that dont deserve to be there because of this. Your stay in prison will not be fun @battleaxe and friends. People are going to want you dead when they find out what you did. I hope you die a slow painful death. You sick mother fuckers.

https://peakd.com/gangstalking/@acousticpulses/electronic-terrorism-and-gaslighting--if-you-downvote-this-post-you-are-part-of-the-problem

Its a terrorist act on American soil while some say its not real or Im a mental case. Many know its real. This is an ignored detrimental to humanity domestic and foreign threat. Ask informed soldiers in the American military what their oath is and tell them about the day you asked me why. Nobody has I guess. Maybe someone told ill informed soldiers they cant protect America from military leaders in control with ill intent. How do we protect locked up soldiers from telling the truth?
0
0
0.000
avatar
Don-1UP-Cheers-Cartel-250px.png

You have received a 1UP from @thecuriousfool!

The following @oneup-cartel family members will soon upvote your post:
@stem-curator, @vyb-curator, @pob-curator, @pal-curator
And they will bring !PIZZA 🍕

Learn more about our delegation service to earn daily rewards. Join the family on Discord.

0
0
0.000
avatar

Congratulations @gabrielr29! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You distributed more than 9000 upvotes.
Your next target is to reach 10000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Support the HiveBuzz project. Vote for our proposal!
0
0
0.000