Advertisement
teslariu

raices

Jun 27th, 2022
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Script que calcula las raices de una ec cuadratica
  6.  
  7. """
  8. from datetime import datetime
  9. from math import sqrt
  10.  
  11. def ingresar_dato(tipo):
  12.     while True:
  13.         try:
  14.             n = float(input(f"Ingrese el coeficiente {tipo}: "))
  15.         except ValueError:
  16.             print("No ha ingresado un número")
  17.         else:
  18.             if tipo == "a" and not n:
  19.                 print("El coeficiente a debe ser no nulo")
  20.                 continue
  21.             return n
  22.  
  23.    
  24. def calcular_raices(a,b,c):
  25.     delta = b**2 - 4*a*c
  26.    
  27.     if delta == 0:
  28.         raiz = -1*b / (2*a)
  29.         return raiz
  30.     elif delta > 0:
  31.         raiz1 = (-1*b + sqrt(delta)) / (2*a)
  32.         raiz2 = (-1*b - sqrt(delta)) / (2*a)
  33.         return [raiz1, raiz2]
  34.     else:
  35.         return "No hay raices"
  36.    
  37.    
  38.    
  39. def imprimir_raices(raices):
  40.     if isinstance(raices, float):
  41.         print("Existe una solución: {:.2f}".format(raices))
  42.     elif isinstance(raices, list):
  43.         print("Existen dos soluciones: {:.2f} y {:.2f}".format(raices[0], raices[1]))
  44.     else:
  45.         print(raices)
  46.        
  47.    
  48.    
  49. def grabar_datos(a,b,c,raices):
  50.     # abro el archivo en modo append, si no existe lo crea
  51.     f = open("resultados.txt","a")
  52.     f.write("\n" + 25*"=" + "\n")
  53.     f.write(datetime.now().strftime("%d/%m/%y %H:%M:%S") + "\n")
  54.     f.write("Parametros:\n")
  55.     f.write(f"a: {a}\n")
  56.     f.write(f"b: {b}\n")
  57.     f.write(f"c: {c}\n")
  58.     if isinstance(raices, float):
  59.         f.write(f"Existe una solución: {raices:.2f}\n")
  60.     elif isinstance(raices, list):
  61.         f.write(f"Existen dos soluciones: {raices[0]:.2f} y {raices[1]:.2f}\n")
  62.     else:
  63.         f.write(f"{raices}\n")
  64.    
  65.     f.close()
  66.  
  67. while True:
  68.     print("\nScript para calcular raices de una ec. cuadrática")
  69.    
  70.     a = ingresar_dato("a")
  71.     b = ingresar_dato("b")
  72.     c = ingresar_dato("c")
  73.     raices = calcular_raices(a,b,c)
  74.     imprimir_raices(raices)
  75.     grabar_datos(a,b,c,raices)
  76.    
  77.    
  78.     opcion = input("Presione cualquier tecla o '1' para salir: ")
  79.     if opcion == "1":
  80.         print("Gracias por usar este programa...")
  81.         break
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement