gpt4 book ai didi

java - 用户输入的二次公式 (Java)

转载 作者:行者123 更新时间:2023-12-02 04:32:21 27 4
gpt4 key购买 nike

我是编码方面的新手,我不太确定如何 100% 地表达这个问题。我试图弄清楚为什么我的程序只存储值“a”的第一个输入,即使该数字是负数。

例如:a= -1(值必须大于 0。再次输入值“a”:)a= 1 b= 3 c= -4

因此,当程序编译时,它仅存储“a”(-1) 的第一个值,而不是第二个值 (1),并在遇到第二个 if 代码块时终止程序。我完全不知道如何解决这个问题:/

这是我的代码:

package quadratic;

import java.util.*;

//Program that does quadratic equations
public class Quadratic{
public static void main(String[] args){

boolean run = true;
while(run){ //if program completes true, will start program again
Scanner sc = new Scanner(System.in); // set scanner to allow user input

System.out.println("Please enter value for 'a':");
double a = (sc.nextDouble()); //looking for user input
if (a <= 0){
System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
sc.nextDouble(); //prompt user again if value less than or equal to 0
}
System.out.println("Please enter value for 'b':");
double b = (sc.nextDouble());
System.out.println("Please enter value for 'c':");
double c = (sc.nextDouble());
System.out.printf("Values entered: a:%s b:%s c:%s \n",a,b,c);

if (Math.pow(b,2)- (4 * a * c) <= 0){
System.out.println("Impossible. Program Terminating");
System.exit(0); //Terminate program
}

double qf1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double qf2 = (-b - Math.sqrt(Math.pow(b, 2) -(4 * a * c)))/ (2 * a);
// qf stands for Quadratic Formula
System.out.printf("Anwser One: %s \n", qf1); //%s whatever qf1 returned
System.out.printf("Anwser Two: %s \n", qf2); //%s whatever qf2 returned
}
}
}

最佳答案

你只要打电话

sc.nextDouble(); //prompt user again if value less than or equal to 0

不是

a = sc.nextDouble(); //prompt user again if value less than or equal to 0

所以,你只是扔掉第二个数字

此外,您可以第二次输入负数,因为您不会检查负数是否小于零(提示:可能是一个循环,直到输入 a 的有效值?)

关于java - 用户输入的二次公式 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31279637/

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