【发布时间】:2014-12-17 11:48:12
【问题描述】:
一段时间以来,我一直在尝试用 Java 创建一个简单的计算器,并且我已经成功地使程序能够处理两个操作数方程(+、-、*、/ 和 ^)。但是,我想知道如何解决单操作数数学问题 - 绝对值(使用符号“|”)、平方根(使用符号 'v')、四舍五入到最接近的整数(使用符号 ' ~')、sin (s)、cos (c) 和 tangent (t)。
我尝试了绝对值操作数,可以在以下位置看到:
if (operator == '|') {
answer = Math.abs(numA);
}
// In the main class
和:
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
// In the maths class
此代码仅在您输入值时才有效,例如:-3 | -3(注意:我注意到它只是执行绝对值运算的第一个数字。第二个数字可以是您想要的任何值(如果你输入了-3 | -4,你的答案仍然是3),只要它确实是一个数字。
任何帮助解决这个问题和帮助找出其他单操作数操作将不胜感激!
提前致谢!
我的程序的源代码如下:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")){
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b' )");
System.out.println("Subtraction: '-' (Ex: 'a - b' )");
System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
System.out.println("Division: '/' (Ex: 'a / b' )");
System.out.println("Exponents: '^' (Ex: 'a ^ b' )");
System.out.println(" ");
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA, numB;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
String s=input.next();
if(s.equals("quit")){
System.out.println("Thank you for using my program!");
System.exit(0);
}
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
}
class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}
【问题讨论】:
-
除非运营商要求,否则不要使用
numB = input.nextDouble()。 -
@Thilo 谢谢!我该怎么做呢?
-
不是很优雅,但您可以将该行移到需要它的每个
if(operator ==块中。 -
这行得通……但就像你说的不太优雅,我有点希望将操作数放在所述数字之前而不是之后
-
在这种情况下,您最好将整行作为字符串读取,并根据需要进行解析。 (看第一个词,看看它是不是可以去那里的运算符等)
标签: java math if-statement operators calculator