![](/img/trans.png)
[英]I'm making a code for a basic number guessing game. There seems to be error with my column on line 7
[英]I'm a beginner in python and I'm trynna code a number guessing game. It keeps giving me a math domain error. Any suggestions pls?
import random
import math
n = int(input("Enter a number between 20 and: "))
number = random.randint(20, n)
print("You have only ", round(math.log(20 - n + 1, 2)), "chances to guess the number!")
attempts = 0
while attempts < round(math.log(20 - n + 1, 2)):
attempts += 1
trial = int(input("Guess the number!: "))
if trial == n:
print("You guessed the number correctly in just ", attempts, "attempts! Well Done")
elif trial < n:
print("Your guess is too low, try again!")
elif trial > n:
print("Your guess is too high, try again!")
if attempts >= round(math.log(20 - n + 1, 2)):
print("You have reached the limit of your number of guesses")
break
好的問題是這個
(20 - n + 1, 2)
假設 n 是 25
20 - 25 = 負 5
我假設您想使用 select 一個高於 20 的數字(n)
如果是這樣,它是一個簡單的修復
(n-20 + 1, 2))
所以你現在得到一個正數
確保你在你擁有它的地方都解決了這個問題
您正在嘗試獲取零或小於零的數字math.log(20 - n + 1, 2)
的log
,並且在數學中未定義零zero or less than zero
的日志,這就是您收到ValueError: math domain error
所以在math.log(20 - n + 1, 2)
和其他log
中確保數字20 - n + 1
大於零>0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.