【每日一题】求一元二次方程的解

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 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值