问题
I'm having trouble understanding the syntax of Java and how to use Java to solve math equations. Below is just an example of a simple equation. I want the program to simply be able to output the result of the calculation. If anyone can help I would greatly appreciate it!
2.6^22 + 3.9^15
回答1:
See also the ScriptEngine.
import java.awt.*;
import java.awt.event.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
class EvaluateString {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout(5,5));
final JTextField input = new JTextField(
"Math.pow(2.6,22)+ Math.pow(3.9,15)",19);
final JTextField output = new JTextField(15);
output.setEditable(false);
gui.add(input, BorderLayout.CENTER);
gui.add(output, BorderLayout.PAGE_END);
// obtain a reference to the JS engine
final ScriptEngine engine = new
ScriptEngineManager().getEngineByExtension("js");
ActionListener calculate = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String s = ((Double)engine.eval(input.getText())).toString();
output.setText(s);
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
};
input.addActionListener(calculate);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
回答2:
Try with
Double sum=Math.pow(2.6, 22) + Math.pow(3.9,15);
System.out.println("sum-->"+sum);
回答3:
How about this:
public class Equ {
public static void main(String[] args)
{
System.out.println(Math.pow(2.6, 22) + Math.pow(3.9,15));
}
}
回答4:
you could use the Math class, here,. in your case you can do:
Double result = Math.pow(2.6,22) + Math.pow(3.9, 15);
that's it,.
回答5:
Use the Math library.
Math.pow(2.6,22) + Math.pow(3.9,15);
This will return a double
The first argument of pow
function is the base and the second argument is the power.
来源:https://stackoverflow.com/questions/17182192/program-that-solves-a-simple-math-equation