我是编码方面的新手,我不太确定如何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/