东软OJ_1021C语言考试练习题_一元二次方程

通过版:


//
//时间:2013年7月14日19:25:31
//
//作者:小代码
//
//编译器:CodeBlocks
//
//题目:
//
//Description
//解一元二次方程ax^2+bx+c=0的解。
//
//Input
//
//a,b,c的值。
//
//
//
//Output
//两个根X1和X2,其中X1>=X2。。
//结果保留两位小数
//
//Sample Input
//1 5 -2
//Sample Output
//0.37 -5.37
//HINT
//
//Source

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

const double ZERO = 0.000001;//代替0
int main( void )
{
    void shijie( double a, double b, double delta, double *px1, double *px2 );//求实根

    double a;
    double b;
    double c;
    double delta;//保存德尔塔的值
    const double ZERO = 0.000001;//代替0
    double x1;//较大的实根
    double x2;//较小的实根

    scanf("%lf%lf%lf",&a,&b,&c);//接收三个参数的值

    delta = b * b - 4 * a * c;//求德尔塔的值

    shijie( a, b, delta, &x1, &x2 );

    printf("%.2lf %.2lf",x1,x2);

    return 0;
}

//求实根
void shijie( double a, double b, double delta, double *px1, double *px2 )
{
    double temp;//交换变量,使得x1>=x2


    *px1 = ( -b + sqrt( delta ) ) / ( 2 * a );
    *px2 = ( -b - sqrt( delta ) ) / ( 2 * a );
    if( *px2 > *px1 )
    {
        temp = *px1;
        *px1 = *px2;
        *px2 = temp;
    }
}

运行效果图:



JAVA通过版:


import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;

public class Main
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		double a;
		double b;
		double c;
		
		Scanner in = new Scanner(System.in);//构造输入对象
		
		//接收三个参数
		a = in.nextDouble();
		b = in.nextDouble();
		c = in.nextDouble();
		
		Test test = new Test( a, b, c );//构造测试对象
		
		test.output();//输出运算结果
	}
}

class Test
{
	public Test()//默认构造函数
	{
		
	}
	
	public Test( double a, double b, double c )//带参构造函数
	{
		this.a = a;
		this.b = b;
		this.c = c;
	}
	
	public void output()//输出结果的共有函数
	{
		this.jie();//调用私有函数求解
		
		DecimalFormat x_out = new DecimalFormat( "#.##" );
		
		
		//System.out.print( x_out.format( this.x1 ) + " " + x_out.format( this.x2 ) );
		
		System.out.printf( "%.2f %.2f",this.x1 , this.x2 );
	}	
	
	
	private double getDelta()//返回德尔塔值得私有函数
	{
		this.delta = this.b * this.b - 4 * this.a * this.c;
		return this.delta;
	}
	
	private void jie()//用公式法求解的私有函数,并保证 x1 >= x2
	{
		this.x1 = ( -b + Math.sqrt( this.getDelta()) ) / ( 2 * this.a );
		this.x2 = ( -b - Math.sqrt( this.getDelta()) ) / ( 2 * this.a );
		
		if( this.x2 > this.x1 )
		{
			double temp;
			temp = this.x1;
			this.x1 = this.x2;
			this.x2 = temp;
		}
	}
	
	private double a;
	private double b;
	private double c;
	private double delta;//保存德尔塔的值
	private double x1;//保存较大的根
	private double x2;//保存较小的根	
}



运行效果图:




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值