Python版:
'''
这是关于用求根公式计算一元二次方程的小程序
作者:Smallk-K
时间:2018年11月30日
'''
import math #引入python的math库,以便使用其中的求根函数sqrt()
#定义一个函数,判断一元二次方程有没有值
def Valid(a,b,c):
if b*b - 4*a*c < 0:
return 0
else:
return 1
#输入abc的值
a = float(input("Please input the value of a:"))
b = float(input("Please input the value of b:"))
c = float(input("Please input the value of c:"))
#如果b2 - 4ac >0 根据求根公式求解,否则输出无值提示
if Valid(a, b, c):
x1 = (-b+math.sqrt(b*b-4*a*c))/2*a
x2 = (-b-math.sqrt(b*b-4*a*c))/2*a
print("The value of x1 is ",x1,"\nThe value of x2 is ",x2)
else:
print("此一元二次方程没有值")
运行结果:
Please input the value of a:1
Please input the value of b:1
Please input the value of c:-2
The value of x1 is 1.0
The value of x2 is -2.0
C语言版:
/*This is a project about Quadratic Equation
*
*Autuor : Small -K
*Time : 2018 -11 - 30
*/
#include <stdio.h>
#include "math.h"
//define a function to valid the square root.
int Valid(int a, int b, int c)
{
if (b * b - 4 * a * c < 0)
{
return 0;
}
else
{
return 1;
}
}
int main()
{
float a, b, c, d, x1, x2; //define the type of data
printf("Please input the values of a,b,c:\n "); //receive the input values of a,b,c
scanf("%f,%f,%f", &a, &b, &c);
//when the values are valid, calculate.
if (Valid(a, b, c))
{
d = b * b - 4 * a * c;
x1 = (-b + sqrt(d)) / (2 * a);
x2 = (-b - sqrt(d)) / (2 * a);
printf("The value of x1 is %.2f and the value of x2 is %.2f \n", x1, x2);
}
else
{
printf("No values\n");
}
}
运行结果:
[menglu@localhost Cproject]$ gcc sqrt.c -lm
[menglu@localhost Cproject]$ ./a.out
Please input the values of a,b,c:
1,1,-2
The value of x1 is 1.00 and the value of x2 is -2.00