Java语言程序设计 例题3.1(代数:解一元二次方程)

*3.1

(Algebra:solve quadratic euations) The two roots of a quadratic equation ax^2+bx+c=0 can be obtain using the following formula:


b^2➖4ac is called the discriminant of the quadratic equation. If it is positive,the equation has two real roots.If it is zero, the equation has one root. If it is negative, the equation has no real roots.
Write a program that prompts the user to enter values for a,b,and c and displays the result based on the discriminant. If the discriminant is positive,display two roots. If the discriminant is 0, display one root. Otherwise,display “The equation has no real roots".
Note that you can use Math.pow(x, 0.5) to compute Vx. Here are some sample runs.

Enter a,b,c:1.0  3  1 
The  equation has two roots -0.381966 and -2361803

Enter a,b,c:1  2.0  1 
The  equation has one root -1

Enter a,b,c:1  2  3
The  equation has no real roots 

*3.1(代数:解一元二次方程)可以使用下面的公式求一元二次方程两个根:



称作一元二次方程的判别式。如果它是正值,那么一元二次方程就有两个实数根。如果它为0,方      程式就只有一个根。如果它是负值,方程式无实数根。
编写程序,提示用户输入a、b和c的值,并且显示基于判别式的结果。如果这个判别式为正,显示两个根。如果判别式为0,显示一个根。否则,显示“The equation has no real roots”(该方程式无实数根)注意,可以使用Math.pow(x,0.5) 来计算。
下面是一些运行示例:
Enter a, b, c:1.0 3 1

The equation has two roots -0.381966 and -2.61803

Enter a, b, c:1 2.0 1

The equation has one root -1.0

Enter a, b, c:1 2 3

The equation has no real roots

import java.util.Scanner;
public class Unite3Test1 
{
	public static void main(String[] args)
	{
	Scanner scan=new Scanner(System.in);
	System.out.println("请输入a的值;");
	int a=scan.nextInt();
	System.out.println("请输入b的值;");
	int b=scan.nextInt();
	System.out.println("请输入c的值;");
	int c=scan.nextInt();
	if((b^2-4*a*c)>0) 
	{
		double m=Math.pow(b^2-4*a*c, 0.5);//题目中给出,m用double定义
		double p=(-b+m)/2*a;
		double q=(-b-m)/2*a;
		System.out.println(p);
		System.out.println(q);
	}else if((b^2-4*a*c)==0) //符合运算时要考虑符号
	{
		double m=Math.pow(b^2-4*a*c, 0.5);
		double r=(-b+m)/2*a;
		System.out.println(r);
	}else
		System.out.println("The equation has no real roots" );
	}

}

结果
 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

差劲的厉害了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值