自定义函数求一元二次方程(算法学习的第十天,C+Java(在学ing))

2020.5.1

学习第十天了吧,我都快记不清日子了~~~

放假的第一天

早起码代码~~

自定义函数求一元二次方程

Java 代码:

import java.util.Scanner;

class Solving {
	int a, b, c;

	Solving(int a, int b, int c) {
		this.a = a;
		this.b = b;
		this.c = c;
	}

	void ShowAnswer() {
		double t = b * b - 4 * a * c;
		double x1 = (double)-b / (2 * a), x2;
		if (t >= 0) {
			x2 = (Math.sqrt(t)) / (2 * a);
			System.out.println("x1=" + String.format("%.3f", x1) + "+" + String.format("%.3f", x2) + " x2=" + String.format("%.3f", x1) + "-" + String.format("%.3f", x2));
		} else {
			x2 = (Math.sqrt(-t)) / (2 * a);
			System.out.println("x1=" + String.format("%.3f", x1) + "+" + String.format("%.3f", x2) + "i x2=" + String.format("%.3f", x1) + "-" + String.format("%.3f", x2) + "i");
		}
	
    }
}

public class SolvingEquation {
	public static void main(String[] args) {
		int a, b, c;
		Scanner input = new Scanner(System.in);
		a = input.nextInt();
		b = input.nextInt();
		c = input.nextInt();
		Solving solv = new Solving(a, b, c);
		solv.ShowAnswer();
	}
}

C 代码

#include<stdio.h>
#include<math.h>
void SolvingEquation(int a, int b, int c);
int main()
{
	int a, b, c;
	scanf("%d%d%d",&a,&b,&c);
	SolvingEquation(a,b,c);
	return 0;
}

void SolvingEquation(int a, int b, int c) 
{
	double t,x;
	x = (double)-b / (2 * a);
	t = (double)(b * b - 4 * a * c);
	if (t >= 0)
		printf("x1=%.3lf+%.3lf x2=%.3lf-%.3lf", x, sqrt(t) / (2 * a), x, sqrt(t) / (2 * a));
	else
		printf("x1=%.3lf+%.3lfi x2=%.3lf-%.3lfi", x, sqrt(-t) / (2 * a), x, sqrt(-t) / (2 * a));
	
}

好好学习,天天向上!!

如有错误恳请大佬指正,感激不尽~~

算法题目来源:https://www.dotcpp.com/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值