gpt4 book ai didi

Java输入法输入小数并处理虚数

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:45 25 4
gpt4 key购买 nike

我想制作一个二次公式程序。我在基础知识上取得了成功,但有两个主要错误。一个是当我尝试输入十进制值作为 a、b 或 c 时,另一个是当我必须处理 i(虚数)时。我该如何解决这些问题?我也很欣赏简化代码的方法,这是我的代码:

import java.util.Scanner;

public class Calculator {
public static void main (String args[]){
System.out.println("Input a");
Scanner ai = new Scanner(System.in);
double a = ai.nextInt();
System.out.println("Input b");
Scanner bi = new Scanner(System.in);
double b = bi.nextInt();
System.out.println("Input c");
Scanner ci = new Scanner(System.in);
double c = ci.nextInt();
double Square1 = Math.pow(b, 2);
double Square2 = -4*a*c;
double Square3 = Square1 + Square2;
double Square = Math.sqrt(Square3);
double Bottom = 2*a;
double Top1 = -b + Square;
double x1 = Top1/Bottom;
double Top2 = -b - Square;
double x2 = Top2/Bottom;
System.out.printf("X = %s", x1);
System.out.printf("X = %s", x2);

}
}

最佳答案

您遇到的第一个错误是因为您使用了方法 nextInt()。当您尝试读取 double 时,它会抛出 InputMismatchException - Method nextInt

您应该使用 nextDouble 方法来代替 nextInt()。

第二个错误:Java 不支持虚数:(

如果你想使用虚数,你必须编写你的类 ImaginaryNumber。

这是您重构的代码:

import java.util.Scanner;

public class Calculator {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);

System.out.println("Input a");
double a = input.nextDouble();

System.out.println("Input b");
double b = input.nextDouble();

System.out.println("Input c");
double c = input.nextDouble();

double square1 = Math.pow(b, 2);
double square2 = -4 * a * c;
double square3 = square1 + square2;

if (square3 < 0) {
double square = Math.sqrt(square3);

double bottom = 2 * a;
double top1 = -b + square;
double x1 = top1 / bottom;
double top2 = -b - square;
double x2 = top2 / bottom;

System.out.printf("X = %s", x1);
System.out.println();
System.out.printf("X = %s", x2);
} else {
System.out
.println("Can not calculate square root for negative number");
}

input.close();

}
}

你可以注意到我添加了

if (square3 < 0) {

这是因为Math.square方法只能取正数。如果传递负数,它将返回 NaN - 不是数字: Math.sqrt

关于Java输入法输入小数并处理虚数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22390347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com