这是我运行程序的主文件:
import math
import Disc
def main():
coeffA = int(input('Enter the coefficient A: '))
coeffB = int(input('Enter the coefficient B: '))
coeffC = int(input('Enter the coefficient C: '))
disc = Disc.discriminant(coeffA, coeffB, coeffC)
while coeffA != 0:
if disc > 0:
solutionOne = (-coeffB + math.sqrt(disc)) / (2 * coeffA)
solutionTwo = (-coeffB - math.sqrt(disc)) / (2 * coeffA)
print('Solutions are: ' + str(solutionOne) + ' and ' + str(solutionTwo))
coeffA = int(input('Enter the coefficient A: '))
coeffB = int(input('Enter the coefficient B: '))
coeffC = int(input('Enter the coefficient C: '))
elif disc == 0:
solutionOne = -coeffB / (2 * coeffA)
print('Solution is: ' + str(solutionOne))
coeffA = int(input('Enter the coefficient A: '))
coeffB = int(input('Enter the coefficient B: '))
coeffC = int(input('Enter the coefficient C: '))
elif disc < 0:
print('Equation has two complex roots.')
coeffA = int(input('Enter the coefficient A: '))
coeffB = int(input('Enter the coefficient B: '))
coeffC = int(input('Enter the coefficient C: '))
else:
print('Program ended.')
# End of the main function
main()
这是你的名字光盘.py计算判别值以在main()函数中使用的文件:
def discriminant(coeffA, coeffB, coeffC):
value = (coeffB ** 2) - (4 * coeffA * coeffC)
return value
这是运行程序时的输出:
Enter the coefficient A: 1
Enter the coefficient B: 2
Enter the coefficient C: -8
Solutions are: 2.0 and -4.0
Enter the coefficient A: 1
Enter the coefficient B: -12
Enter the coefficient C: 36
Solutions are: 9.0 and 3.0
Enter the coefficient A: 2
Enter the coefficient B: 9
Enter the coefficient C: -5
Solutions are: -0.75 and -3.75
Enter the coefficient A: 4
Enter the coefficient B: 6
Enter the coefficient C: 20
Solutions are: 0.0 and -1.5
Enter the coefficient A: 0
Enter the coefficient B: 0
Enter the coefficient C: 0
Program ended.
我期待以下根与上述输入:
Run1: 2, -4
Run2: 6
Run3: .5, -5
Run4: 'Equation has two complex roots.'
当我运行程序时,程序运行的最后3次的输出都是错误的,并且似乎将鉴别器设置为大于0的值,当我期望它根据计算的鉴别器更改输出时。提前谢谢!你知道吗
你好像少了一对括号。 这将修复错误:
找到了解决办法。我的判别函数在while语句之外,因此当从用户输入3个变量时,它会在每个循环中保持计算出的第一个判别函数,这就是为什么每次运行都会产生2个答案的原因。通过将判别函数的位置更改为while语句内部,它现在将重新计算while语句的每个循环的判别函数。这是解决此问题的正确代码:
产生的正确输出代码如下:
感谢Stack Overflow社区提供的所有帮助和建议!你知道吗
相关问题 更多 >
编程相关推荐