Java咩 2021-03-11 23:47 采纳率: 0%
浏览 150
已结题

PTA中使用java求解一元二次方程的解,部分答案不正确,求大佬指导

问题:

本题目要求读入一元二次方程3个系数A、B、C,然后输出方程的解。

输入格式:

有多组输入,每组在一行中给出3个绝对值不超过1000的整数A、B、C。

输出格式:

对每一组输入,在一行中输出X值,保留2位小数。若有多个解,用逗号隔开。

输入样例:

在这里给出一组输入。例如:

1 2 1
1 3 2
1 2 3

输出样例:

在这里给出相应的输出。例如:

x=-1.00
x1=-1.00,x2=-2.00
x1=-1.00+1.41i,x2=-1.00-1.41i

 以下为我的代码:

import java.util.Scanner;
class Main3 {
    /**
     * 解题思路
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true){
            // 以字符串 coefficient 接收输入数据,Next(); 无法接收空格内容
            // 所以要用 nextLine(); 进行接收
            String coefficient = sc.nextLine();
            // 调用String.parseFloat 方法,用空格截取字符串
            // 注意截取时最好用"\\s+",而不是" ",后者只能截取一个空格
            String[] arr = coefficient.split(" ");
            int a = Integer.parseInt(arr[0]);
            int b = Integer.parseInt(arr[1]);
            int c = Integer.parseInt(arr[2]);
            SolvingEquations(a, b, c);
        }
    }

    public static void SolvingEquations(int a, int b, int c) {
        double delta = b * b - 4 * a * c;
        double x1, x2;
        if (delta == 0) {
            x1 = -b / (2 * a);
            System.out.println("x=" + String.format("%.2f", x1));
        } else if (delta > 0) {
            x1 = (-b + Math.sqrt(delta)) / (2 * a);
            x2 = (-b - Math.sqrt(delta)) / (2 * a);
            System.out.println("x1=" + String.format("%.2f", x1) + ",x2=" + String.format("%.2f", x2));
        } else if (delta < 0) {
            double real = -b / (2 * a);
            double imaginaryPart = Math.sqrt(-delta) / (2 * a);
            // x = real + imaginaryPart*i
            if (real == 0) {
                System.out.println("x1=" + String.format("%.2f", imaginaryPart) + "i" + ",x2=" + "-" + String.format("%.2f", imaginaryPart) + "i");
            } else {
                System.out.println("x1=" + String.format("%.2f", real) + "+" + String.format("%.2f", imaginaryPart) + "i" + ",x2=" + String.format("%.2f", real) + "-" + String.format("%.2f", imaginaryPart) + "i");
            }
        }
    }
}

测试结果:(正确无误)

 提交运行结果:

 

 

 
  • 写回答

1条回答 默认 最新

  • 关注

    测试点0、1、2、3是什么?

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月1日

悬赏问题

  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络
  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥30 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物