J'essaie de créer une fonction qui calcule la moyenne arithmétique, la moyenne géométrique et la moyenne harmonique des nombres que l'utilisateur me donne. le résultat devrait être comme: pour les nombres 4 et 9 La moyenne arithmétique des nombres est 6,5 La moyenne géométrique des nombres est 6 La moyenne harmonique des nombres est 5,538461538461538
c'est mon code:
import math def fancy_mean(): number=input("Please enter the numbers, one in each line: ") total_arithmetic=0 multiplication_result_geometric=1 harmonical_total=0 count_of_numbers=0 list_of_numbers=[] while number!="": number=float(number) list_of_numbers.append(number) count_of_numbers+=1 for i in list_of_numbers: total_arithmetic=total_arithmetic+i arithmatic_mean=float(total_arithmetic/count_of_numbers) multiplication_result_geometric=multiplication_result_geometric*i geomatric_mean=float(math.sqrt(multiplication_result_geometric)) harmonical_total=harmonical_total+(1/i) harmonical_mean=float(count_of_numbers/harmonical_total) number=input("Please enter the numbers, one in each line: ") if not list_of_numbers: return print("The arithmetic mean of the numbers is",arithmatic_mean) print("The geometric mean of the numbers is",geomatric_mean) print("The harmonic mean of the numbers is",harmonical_mean)
mais je continue à obtenir de mauvais résultats et je ne sais pas pourquoi? La moyenne arithmétique des nombres est 8,5 La moyenne géométrique des nombres est 12,0 La moyenne harmonique des nombres est 3,2727272727272725 entrer la description de l'image ici
3 Réponses :
Vous recalculez constamment les moyennes au lieu d'ingérer tous les nombres et de les calculer une fois. J'ai déplacé le calcul en dehors de la boucle while:
import math def fancy_mean(): number=input("Please enter the numbers, one in each line: ") total_arithmetic=0 multiplication_result_geometric=1 harmonical_total=0 count_of_numbers=0 list_of_numbers=[] while number != "": number=float(number) list_of_numbers.append(number) count_of_numbers+=1 number=input("Please enter the numbers, one in each line: ") for i in list_of_numbers: total_arithmetic=total_arithmetic+i arithmatic_mean=float(total_arithmetic/count_of_numbers) multiplication_result_geometric=multiplication_result_geometric*i geomatric_mean=float(math.sqrt(multiplication_result_geometric)) harmonical_total=harmonical_total+(1/i) harmonical_mean=float(count_of_numbers/harmonical_total) if not list_of_numbers: return print("The arithmetic mean of the numbers is",arithmatic_mean) print("The geometric mean of the numbers is",geomatric_mean) print("The harmonic mean of the numbers is",harmonical_mean) fancy_mean()
merci, cela a fonctionné, et je devrais également obtenir Aucun si la liste est vide, ce qui signifie qu'un utilisateur n'a pas entré de chiffres, mais dans ce cas, je termine le processus avec le code de sortie 0 / comment puis-je le réparer?
@ZivAqua Changez simplement la partie qui dit if not list_of_numbers: return
Une instruction return
sans valeur renverra None, donc je ne comprends pas vraiment le problème?
À moins que vous n'ayez une bonne raison de ne pas utiliser les implémentations existantes de ces fonctions, je vous fancy_mean
déclarer fancy_mean
et d'utiliser les implémentations SciPy et NumPy de moyenne géométrique, de moyenne harmonique et de moyenne .
De plus, le code n'a pas d'instruction de return
, et ce sera probablement à cause d'une possible boucle infinie (je suppose que l'indentation est OK dans votre environnement).
Voici une version SciPy / NumPy de votre fonction, sans l'invite de nouveaux numéros:
from scipy.stats.mstats import gmean, hmean import numpy as np my_numbers = [4, 9] def fancy_mean(numbers): return gmean(numbers), hmean(numbers), np.mean(numbers) fancy_mean(my_numbers) # >>> (6.0, 5.538461538461538, 6.5)
Vous pouvez calculer les moyennes intermédiaires en déplaçant l'instruction d'impression à l'intérieur de la boucle, en corrigeant de nombreuses erreurs d'orthographe de vos variables et en demandant également de nouveaux nombres à l'intérieur de la boucle. Vous laissez la boucle avec une instruction break
si une chaîne vide est fournie et que vous gérez gracieusement les entrées non flottantes:
Please enter the next number, currently you have []: 1 The arithmetic mean of the numbers is 1.0 The geometric mean of the numbers is 1.0 The harmonic mean of the numbers is 1.0 Please enter the next number, currently you have [1.0]: 4 The arithmetic mean of the numbers is 2.5 The geometric mean of the numbers is 2.0 The harmonic mean of the numbers is 1.6 Please enter the next number, currently you have [1.0, 4.0]: 4 The arithmetic mean of the numbers is 3.0 The geometric mean of the numbers is 2.5198420997897464 The harmonic mean of the numbers is 2.0
Production:
import math def fancy_mean(): arithmetic_total = 0 multiplication_result_geometric = 1 harmonical_total = 0 numbers = [] len_numbers = 0 while True: number = input(f"\nPlease enter the next number, currently you have {numbers}:") if not number: # empty string: exit break try: n = float(number) numbers.append(n) except ValueError: print("Not a number!") continue # back to the start of the loop len_numbers += 1 # you can use len(numbers) instead as well # sum numbers / count numbers arithmetic_total += n arithmetic_mean = float(arithmetic_total/len_numbers) # nth root of product of n numbers multiplication_result_geometric *= n geometric_mean= multiplication_result_geometric ** (1/len_numbers) # count numbers / sum (1/number for number in numbers) harmonical_total += 1/n harmonical_mean = len_numbers / harmonical_total print("The arithmetic mean of the numbers is", arithmetic_mean) print("The geometric mean of the numbers is", geometric_mean) print("The harmonic mean of the numbers is", harmonical_mean) fancy_mean()
IndentationError's (comme dans multiple). Et pas le code que vous exécutez - actuellement, il a une boucle sans fin parce que vous ne réinitialisez jamais le
number
dans votre boucle whilewhile number != "":
Boucle. L'indentation est importante, veuillez modifier et corriger votre code. A côté de cela - vous n'appelez jamaisfancy_mean()
- donc rien ne devrait se passer du tout. exemple minimal reproductible !