Python中使用while循环的自然对数

2024-09-30 14:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

函数:y(x)=ln1/(1-x)

我如何编写Python程序来计算用户指定的x值的上述函数,其中ln是自然对数(以e为底的对数)?我将强制使用while循环,以便程序对输入到程序中的x的每个合法值重复计算。当输入非法值“x”时,我使用break终止程序

我已尝试使用以下代码,但似乎运行不正常:

import math

n = int(input("Enter the number to be converted: "))

while n >= 0:
    if n <= 0:    
        break

print("Your number is not positive terminating program.") 
    
x = math.log(n) * 1/(1-n)

print("The Log Value is:", x)

Tags: 函数代码用户import程序numberis对数
2条回答

所以实际上,在while循环中没有合适的行

import math
valid = True

while valid == True:
    n = int(input("Enter the number to be converted: "))
    if n <= 0:
        print("Your number is not positive terminating program.")     
        valid = False
    else:
        x = math.log(n) * 1/(1-n)

        print("The Log Value is:", x)

尝试:

import math

while True: # infinite loop, to be halted by break
    x = float(input('Enter the number to be converted: ')) # get the input
    if x >= 1: # is the input legal?
        print('The function cannot be evaluated at x >= 1.')
        break # break out of the loop if the input is "illegal"
    y = math.log(1 / (1 - x))
    print('The log value is:', y)
  1. 首先,您的程序可能陷入无限循环;例如,如果输入n = 1,则n >= 0为真n <= 0为假,因此程序无限期地运行while循环

  2. 函数的“合法输入”必须是(实)数(严格地)小于1。如果n == 1,那么您正在进行零除运算。如果n > 1,则在log函数中输入一个负数

在建议的代码中,我只检查输入的“数字合法性”;i、 例如,输入一个空字符串将抛出一个错误。但我认为这超出了你在作业中的要求

相关问题 更多 >