Advertisement
teslariu

cuad+errores

Oct 25th, 2021
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Script que calcula las raíces de una ecuación cuadrática en el campo de
  6. los nros. reales
  7. """
  8.  
  9. import datetime # para agregar fecha y hora
  10.  
  11.  
  12. def ingresar_datos(tipo):
  13.     while True:
  14.         try:
  15.             numero = float(input(f"Ingrese el {tipo}: "))
  16.         except ValueError:
  17.             print("No has ingresado un número")
  18.         else:
  19.             if tipo == "término cuadrático (a)" and not numero:
  20.                 print("Debes ingresar un número distinto de cero")
  21.             else:
  22.                 return numero
  23.        
  24.    
  25. def calcular_raices(a,b,c):
  26.     from math import sqrt
  27.     delta = b**2 - 4*a*c
  28.    
  29.     if not delta: # if delta == 0:
  30.         raiz = -1*b / (2*a)
  31.         return raiz
  32.        
  33.     elif delta > 0:
  34.         raiz1 = (-1*b + sqrt(delta)) / (2*a)
  35.         raiz2 = (-1*b - sqrt(delta)) / (2*a)
  36.         return [raiz1, raiz2]
  37.    
  38.     else:
  39.         return "No hay soluciones reales"
  40.        
  41.  
  42.  
  43. def imprimir(raices):
  44.     if isinstance(raices, float):
  45.         print("Existe una solución: {:.2f}".format(raices))
  46.     elif isinstance(raices, list):
  47.         print("Existen dos soluciones: {:.2f} y {:.2f}".format(raices[0], raices[1]))
  48.     else:
  49.         print(raices)
  50.        
  51.        
  52. def grabar_datos(a,b,c,raices):
  53.     """Grabo fecha, hora, parámetros y raíces"""
  54.     f.write(datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S"))
  55.     f.write("\n--------------------------------------------------------\n")
  56.     f.write(f"a: {a}\n")
  57.     f.write(f"b: {b}\n")
  58.     f.write(f"c: {c}\n")
  59.     if isinstance(raices, float):
  60.         f.write("Existe una solución: {:.2f}".format(raices) )
  61.     elif isinstance(raices, list):
  62.         f.write("Existen dos soluciones: {:.2f} y {:.2f}".format(raices[0], raices[1]))
  63.     else:
  64.         f.write(raices)
  65.     f.write("\n\n")
  66.  
  67.  
  68.  
  69.  
  70. ##############################################################
  71.  
  72. # si el archivo cuadratica.txt no existe lo creo
  73. try:      
  74.     f = open("cuadratica.txt", "x")
  75. except FileExistsError:        
  76.     f = open("cuadratica.txt","a")
  77.  
  78.  
  79. print("Cálculo de las raíces de una ecuación cuadrática")
  80.  
  81. while True:
  82.     print()
  83.     a = ingresar_datos("término cuadrático (a)")
  84.     b = ingresar_datos("término lineal (b)")
  85.     c = ingresar_datos("término independiente (c)")
  86.    
  87.    
  88.     raices = calcular_raices(a,b,c)
  89.     grabar_datos(a,b,c,raices)
  90.     imprimir(raices)
  91.        
  92.     opcion = input("Presione 1 para salir u otra tecla para continuar: ")
  93.     if opcion == "1":
  94.         print("Cerrando archivos...")
  95.         f.close()
  96.         break
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement