計算器實現演算法
Ⅰ 計算器演算法程序
extern "C"
{
__declspec(dllexport)
int WINAPI icePub_bigIntegerCalculate(char *strArithmetic,char *strResult);
}
#pragma comment(lib,"icePubDll.lib")
char strResult[1024];
icePub_bigIntegerCalculate("12345+876154321",strResult);
AfxMessageBox(strResult);
icePub_bigIntegerCalculate("1234567719012345677190-8176154321",strResult);
AfxMessageBox(strResult);
icePub_bigIntegerCalculate("13579*86421",strResult);
AfxMessageBox(strResult);
icePub_bigIntegerCalculate("1234567719/112233",strResult);
AfxMessageBox(strResult);
Ⅱ 求java Swing的計算器演算法
/**
* 簡單的計算器程序
*
*/
import java.awt.*;
import java.awt.event.*;
public class CalcAppDemo extends Frame{
private TextField t_result;
private Panel p_main; //主面板
private Panel p_num; //數字面板
private Panel p_oper; //操作符面板
private Panel p_show; //顯示面板
private Button b_num[]; //數字按鈕
private Button b_oper[]; //操作符面板
public CalcAppDemo(String title){
setTitle(title);
t_result = new TextField("0.0", 21);
p_main = new Panel();
p_num = new Panel();
p_oper = new Panel();
p_show = new Panel();
p_main.setLayout(new BorderLayout());
p_num.setLayout(new GridLayout(4, 3, 1, 1));
p_oper.setLayout(new GridLayout(4, 2, 1, 1));
b_num = new Button[12];
for(int i=0; i<9; i++)
{
b_num = new Button(new Integer(i+1).toString());
}
b_num[9] = new Button("0");
b_num[10] = new Button("cls");
b_num[11] = new Button(".");
for(int i=0; i<12; i++)
{
p_num.add(b_num);
}
b_oper = new Button[8];
b_oper[0] = new Button("+");
b_oper[1] = new Button("-");
b_oper[2] = new Button("*");
b_oper[3] = new Button("/");
b_oper[4] = new Button("pow");
b_oper[5] = new Button("sqrt");
b_oper[6] = new Button("+/-");
b_oper[7] = new Button("=");
for(int i=0; i<8; i++) //
{
p_oper.add(b_oper);
}
t_result.setEditable(false);
p_show.add(t_result, BorderLayout.NORTH);
p_main.add(p_show, BorderLayout.NORTH);
p_main.add(p_num, BorderLayout.WEST);
p_main.add(p_oper, BorderLayout.EAST);
this.add(p_main, BorderLayout.CENTER);
setSize(400, 400);
setResizable(false);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
ButtonListener b1 = new ButtonListener();
for(int i=0; i<12; i++)
{
b_num.addActionListener(b1);
}
for(int i=0; i<8; i++)
{
b_oper.addActionListener(b1);
}
}
class ButtonListener implements ActionListener
{
private String lastOp; //存儲上一此操作符
private String strVal; //存儲數字對應的字元串
private double total; //總數
private double number; //存儲新輸入的數
private boolean firsttime; //判斷是否第一次按下的是操作符按鈕
private boolean operatorPressed;//判斷是否已經按過操作符按鈕
ButtonListener()
{
firsttime = true;
strVal = "";
}
//事件處理器
public void actionPerformed(ActionEvent e)
{
String s = ((Button)e.getSource()).getLabel().trim();
if(Character.isDigit(s.charAt(0)))
{//判斷是操作數還是操作符
handleNumber(s);
}
else
{
calculate(s);
}
}
//判斷是一元操作符還是二元操作符,並根據操作符類型做計算
void calculate(String op)
{
operatorPressed = true;
if(firsttime&&! isUnary(op))
{
total = getNumberOnDisplay();
firsttime = false;
}
if(isUnary(op))
{
handleUnaryOp(op);
}
else if(lastOp != null)
{
handleBinaryOp(lastOp);
}
if(! isUnary(op))
{
lastOp = op;
}
}
//判斷是否一元操作符
boolean isUnary(String s)
{
return s.equals("=")
||s.equals("cls")||s.equals("sqrt")
||s.equals("+/-")||s.equals(".");
}
//處理一元操作符
void handleUnaryOp(String op)
{
if(op.equals("+/-"))
{//
number = negate(getNumberOnDisplay() + "");
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("."))
{
handleDecPoint();
return;
}else if(op.equals("sqrt"))
{
number = Math.sqrt(getNumberOnDisplay());
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("="))
{//
if(lastOp!= null && !isUnary(lastOp))
{
handleBinaryOp(lastOp);
}
lastOp = null;
firsttime = true;
return;
}else
{
clear();
}
}
//處理二元運算符
void handleBinaryOp(String op)
{
if(op.equals("+"))
{
total +=number;
}else if(op.equals("-"))
{
total -=number;
}else if(op.equals("*"))
{
total *=number;
}else if(op.equals("/"))
{
try
{
total /=number;
}catch(ArithmeticException ae){}
}else if(op.equals("pow"))
total = Math.pow(total, number);
//t_result.setText("");
lastOp = null;
// strVal = "";
number = 0;
t_result.setText(total + "");
}
//該方法用於處理數字按鈕
void handleNumber(String s)
{
if(!operatorPressed)
{
strVal += s;
}else
{
operatorPressed = false;
strVal = s;
}
//
number = new Double(strVal).doubleValue();
t_result.setText("");
t_result.setText(strVal);
}
//該方法用於按下"."按鈕
void handleDecPoint()
{
operatorPressed = false;
//
if(strVal.indexOf(".")<0)
{
strVal += ".";
}
t_result.setText("");
t_result.setText(strVal);
}
//該方法用於將一個數求反
double negate(String s)
{
operatorPressed = false;
//如果是一個整數,去掉小數點後面的0
if(number == (int)number)
{
s = s.substring(0,s.indexOf("."));
}
//如果無"-"增加在該數的前面
if(s.indexOf("-")<0)
{
strVal = "-" + s;
}
else
{
strVal = s.substring(1);
}
return new Double(strVal).doubleValue();
}
//將顯示框中的值轉換成Double
double getNumberOnDisplay()
{
return new Double(t_result.getText()).doubleValue();
}
//清除屏幕並設置所有的標識
void clear()
{
firsttime = true;
lastOp = null;
strVal = "";
total = 0;
number = 0;
t_result.setText("0");
}
}
public static void main(String[] args) {
CalcAppDemo c = new CalcAppDemo("簡單的計算器程序");
c.setVisible(true);
}
}
Ⅲ java寫的windows系統的計算器演算法
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Calculator
{
public static void main(String[] args)
{
int first,second;
char operator;
try {
BufferedReader firstin = new BufferedReader ( new InputStreamReader (System.in));
BufferedReader secin = new BufferedReader ( new InputStreamReader (System.in));
BufferedReader oper = new BufferedReader ( new InputStreamReader (System.in));
System.out.print("please enter the first value:");
first=Integer.parseInt(firstin.readLine());
System.out.print("please enter the second value:");
second=Integer.parseInt(secin.readLine());
System.out.print("please enter the operator:");
String temp=oper.readLine();
operator=temp.charAt(0);
new Calculator(first,second,operator);
} catch (Exception e) {
System.out.print("Unwanted input detected!");
}
}
Calculator(int first,int second,char oper)
{
switch(oper)
{
case '+': System.out.print(first+second);break;
case '-': System.out.print(first-second);break;
case '*': System.out.print(first*second);break;
case '/': System.out.print(first/second);break;
default:System.out.print("please!");
}
}
} 試試這個
Ⅳ 怎樣用java 實現計算器的 演算法
package com.t.core.util;
/**
* 數學計算工具類
*
* @author Administrator
*
*/
publicclassMathUtil {
// ----------------三角運算----------------------
/**
* 弧度轉化為角度
*
* @param degress
* @return
*/
publicstaticdouble toDegress(double degress) {
return Math.toDegrees(degress);
};
/**
* 角度轉化為弧度
*
* @param radians
* @return
*/
publicstaticdouble toRadians(double radians) {
return Math.toRadians(radians);
};
/**
* 反餘弦
*
* @param acos
* @return角度范圍在0.0到pi之間
*/
publicstaticdouble aCos(double acos) {
return Math.acos(acos);
};
/**
* 反正弦
*
* @param asin
* @return角度范圍在-pi/2到pi/2之間
*/
publicstaticdouble aSin(double asin) {
return Math.asin(asin);
};
/**
* 反正切
*
* @param atan
* @return角度范圍在-pi/2到pi/2之間
*/
publicstaticdouble aTan(double atan) {
return Math.atan(atan);
};
/**
* 三角餘弦
*
* @param cos
* @return
*/
publicstaticdouble cos(double cos) {
return Math.cos(cos);
};
/**
* 雙曲餘弦
*
* @param cosh
* @return
*/
publicstaticdouble cosH(double cosh) {
return Math.cosh(cosh);
};
/**
* 正弦
*
* @param sin
* @return
*/
publicstaticdouble sin(double sin) {
return Math.sin(sin);
};
/**
* 雙曲正弦
*
* @param sinh
* @return
*/
publicstaticdouble sinH(double sinh) {
return Math.sinh(sinh);
};
/**
* 三角正切
*
* @param tan
* @return
*/
publicstaticdouble tan(double tan) {
return Math.tan(tan);
};
/**
* 雙曲正切
*
* @param tanh
* @return
*/
publicstaticdouble tanH(double tanh) {
return Math.tanh(tanh);
};
/**
* 將矩形坐標(x,y)轉換成極坐標(r,thet)
*
* @param x
* @param y
* @return
*/
publicstaticdouble aTan2(double x, double y) {
return Math.atan2(x,y);
};
// ----------------取整運算------------------
/**
* 取整,返回小於目標數的最大整數(地板函數)
*
* @param number
* @return
*/
publicstaticdouble floor(double number) {
return Math.floor(number);
};
/**
* 取整,返回大於目標數的最小整數(天花板函數)
*
* @param number
* @return
*/
publicstaticdouble ceil(double number) {
return Math.ceil(number);
};
/**
* 四捨五入取整
*
* @param number
* @return
*/
publicstaticdouble round(double number) {
return Math.round(number);
};
publicstaticfloat round(float number) {
return Math.round(number);
};
/**
* 平方根
*
* @param number
* @return
*/
publicstaticdouble sqrt(double number) {
return Math.sqrt(number);
};
/**
* 立方根
*
* @param number
* @return
*/
publicstaticdouble cbrt(double number) {
return Math.cbrt(number);
};
/**
* 歐拉數e的n次冪
*
* @param number
* @return
*/
publicstaticdouble exp(double number) {
return Math.exp(number);
};
/**
* sqrt(x2+y2),沒有中間溢出或下溢
*
* @param number
* @param number2
* @return
*/
publicstaticdouble hypot(double number, double number2) {
return Math.hypot(number,number2);
};
/**
* 按照IEEE754標准規定,對兩個參數進行余數運算
*
* @param number
* @param number2
* @return
*/
publicstaticdouble IEEEremainder(double number, double number2) {
return Math.IEEEremainder(number,number2);
};
/**
* 乘方
*
* @param number
* @param number2
* @return
*/
publicstaticdouble pow(double number, double number2) {
return Math.pow(number,number2);
};
/**
* 自然對數
*
* @param number
* @return
*/
publicstaticdouble log(double number) {
return Math.log(number);
};
/**
* 底數為10的對數
*
* @param number
* @return
*/
publicstaticdouble log10(double number) {
return Math.log10(number);
};
/**
* 參數與1之和的自然對數
*
* @param number
* @return
*/
publicstaticdouble log1p(double number) {
return Math.log1p(number);
};
// ------------符號相關運算------------------
/**
* 絕對值
*
* @param number
* @return
*/
publicstaticdouble abs(double number) {
return Math.abs(number);
};
publicstaticint abs(int number) {
return Math.abs(number);
};
publicstaticfloat abs(float number) {
return Math.abs(number);
};
publicstaticlong abs(long number) {
return Math.abs(number);
};
/**
* 符號賦值
*
* @param magnitude
* @param sign
* @return帶有第二個浮點數符號的第一個浮點參數
*/
publicstaticdouble Sign(double magnitude, double sign) {
return Math.Sign(magnitude,sign);
};
publicstaticfloat Sign(float magnitude, float sign) {
return Math.Sign(magnitude,sign);
};
/**
* 符號函數
*
* @param number
* @return number等於0,返回0;number大於0,返回1;number小於0,返回-1
*/
publicstaticfloat Sign(float number) {
return Math.signum(number);
};
publicstaticdouble Sign(double number) {
return Math.signum(number);
};
/**
* 找出最大值
*
* @param number
* @param number2
* @return
*/
publicstaticdouble max(double number, double number2) {
return Math.max(number,number2);
};
publicstaticint max(int number, int number2) {
return Math.max(number,number2);
};
publicstaticfloat max(float number, float number2) {
return Math.max(number,number2);
};
publicstaticlong max(long number, long number2) {
return Math.max(number,number2);
};
/**
* 計算最小值
*
* @param number
* @param number2
* @return
*/
publicstaticlong min(long number, long number2) {
return Math.min(number,number2);
};
publicstaticint min(int number, int number2) {
return Math.min(number,number2);
};
publicstaticfloat min(float number, float number2) {
return Math.min(number,number2);
};
publicstaticdouble min(double number, double number2) {
return Math.min(number,number2);
};
/**
*
* @param start
* @param direction
* @return第一個參數和第二個參數之間與第一個參數相鄰的浮點數
*/
publicstaticdouble nextAfter(double start, double direction) {
return Math.nextAfter(start,direction);
};
publicstaticfloat nextAfter(float start, float direction) {
return Math.nextAfter(start,direction);
};
/**
*
* @param number
* @return比目標數略大的浮點數
*/
publicstaticfloat nextUp(float number) {
return Math.nextUp(number);
};
publicstaticdouble nextUp(double number) {
return Math.nextUp(number);
};
/**
* 隨機數
*
* @return
*/
publicstaticdouble random() {
return Math.random();
};
}
Ⅳ 計算器上的百分比是怎麼演算法
用男人的人數除以總人數,然後乘百分之百,就是百分比
計算器的方法就是這樣的,因為這不是方差或是平均數之類的,所以不用統計
Ⅵ 誰能告訴我科學計算器的演算法謝謝!
非常非常簡單 開啟屏幕旋轉 打開計算器 將手機旋轉到橫屏模式,你看到的計算器界面就變成科學計算器了 已經算過的記錄貌似不能保存。有個方法,那就是算完後截屏,然後再圖片里就能找到了。
Ⅶ 編寫一個完整的計算器演算法。要求1)對計算器有輸入中綴表達式、計算、輸出等2)各項內容以菜單式進行操作
我以前寫了一個計算器,你要的話我給你!不過代碼不是規很范,要的話告訴我一聲。。。
Ⅷ java編程實現計算器
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame implements ActionListener {
private String s_show;
private String s_go;
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3=new Panel();
Oper do1 = new Oper();
TextField textfields = new TextField(27);
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
Calculator() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
MenuBar mbr=new MenuBar();
setMenuBar(mbr);
Menu edit=new Menu(" do ");
MenuItem =new MenuItem("Copy Ctrl+C");
MenuItem zhantie=new MenuItem(" Ctrl+V");
MenuItem exit=new MenuItem("Close Alt+F4");
edit.add();
edit.add(zhantie);
mbr.add(edit);
Menu help=new Menu(" help ");
MenuItem help1=new MenuItem("help theme");
MenuItem about=new MenuItem("about us");
dlog.setAlwaysOnTop(true);
dlog.setResizable(false);
//dlog.setEnabled(false);
s1="學習時興趣小組做的";
aboutlab.setSize(200, 150);
aboutlab.setText(s1);
dlog.add(aboutlab);
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dlog.setVisible(true);
}
});
dlog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dlog.setVisible(false);
}
});
help.add(help1);
help.add(about);
mbr.add(help);
p1.setBackground(Color.lightGray);
p1.setForeground(Color.red);
p2.setBackground(Color.lightGray);
p2.setForeground(Color.blue);
p1.setLayout(new FlowLayout(FlowLayout.RIGHT, 1,1));
p1.add(textfields);
p1.add(buttons1);
buttons1.addActionListener(this);
p2.setLayout(new GridLayout(5, 4, 10, 16));
this.add(p1, BorderLayout.CENTER);
this.add(p2, BorderLayout.SOUTH);
this.setTitle("Play the window");
this.setResizable(false);
this.setAlwaysOnTop(true);
/**textfields.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
char c=e.getKeyChar();
String textfieldsstr=textfields.toString();
switch(c){
case 1:textfields.setText(textfieldsstr+1);break;
case 2:textfields.setText(textfields.toString()+2);break;
case 3:textfields.setText(textfields.toString()+3);break;
case 4:textfields.setText(textfields.toString()+4);break;
case 5:textfields.setText(textfields.toString()+5);break;
case 6:textfields.setText(textfields.toString()+6);break;
case 7:textfields.setText(textfields.toString()+7);break;
case 8:textfields.setText(textfields.toString()+8);break;
case 9:textfields.setText(textfields.toString()+9);break;
case 0:textfields.setText(textfields.toString()+0);break;
case '*':textfields.setText(textfields.toString()+"*");break;
}
/**if(e.getKeyChar()==1){
textfields.setText(textfields.toString()+1);
}
}
});*///未實現鍵盤監聽
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
screenWidth=screenSize.width;
screenHeight=screenSize.height;
this.setBounds(screenWidth/2-150, screenHeight/2-128, 300, 256);
dlog.setBounds(screenWidth/2-100, screenHeight/2-78, 200, 150);
int i, j = 0, k = 9, r1 = 0, r2 = 0, r3 = 0;
for (i = 0; i < 20; i++) {
j++;
if (j == 4) {
j = 0;
r1++;
Button buttons2_i = new Button();
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r1) {
case 1:
buttons2_i.setLabel("+");
break;
case 2:
buttons2_i.setLabel("-");
break;
case 3:
buttons2_i.setLabel("*");
break;
case 4:
buttons2_i.setLabel("/");
break;
case 5:
buttons2_i.setLabel("=");
break;
}
}// endif
else // else1
{
if (i < 3) {
r2++;
Button buttons2_i = new Button(""); //
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r2) {
case 1:
buttons2_i.setLabel("(");
break;
case 2:
buttons2_i.setLabel(")");
break;
case 3:
buttons2_i.setLabel("sqrt");
break;
}
}// endif
else {
if (i > 16 && i < 19) {
r3++;
Button buttons2_i = new Button("");
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
switch (r3) {
case 1:
buttons2_i.setLabel(".");
break;
case 2:
buttons2_i.setLabel("CE");
break;
}
}// endif
else {
Integer name = new Integer(k);
k--;
s_show = name.toString();
Button buttons2_i = new Button(s_show);
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
}
}
}// end else1
}// end for
s_show = "";
s_go = "";
this.setVisible(true);
}// end Calculator()構造方法
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) // if1
{
if (e.getActionCommand() == "CE")// Del
{
s_show = "";
s_go = "";
textfields.setText(s_show);
} else if (e.getActionCommand() == "Backspace") {
if (s_show.equals("")) {
s_go = "";
textfields.setText("");
} else {
if (s_go.length() > 0)
s_go = s_go.substring(0, s_go.length() - 1);
s_show = s_show.substring(0, s_show.length() - 1);
textfields.setText(s_show);
}
} else if (e.getActionCommand() == ".") {
if (textfields.getText().equals(""))
textfields.setText("0.");
else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
if (e.getActionCommand() != "=") {
if (e.getActionCommand().equals("sqrt")) {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
s_go = s_go.substring(0, s_go.length() - 3);
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(do1.operator(s_go)); // ().toString()
}
}// end else
}// end if1
if(e.getSource()==""){
sedit=textfields.getSelectedText();
StringSelection text=new StringSelection(sedit);
clp.setContents(text, null);
}
/**else if(e.getSource()=="zhantie"){
Transferable contents=clp.getContents(this);//返回表示剪貼板當前內容的 transferable 對象。
DataFlavor flavor=DataFlavor.stringFlavor;//
String ss;
if (contents.isDataFlavorSupported(flavor)) {
try
{
int start=textfields.getSelectionStart();
int end=textfields.getSelectionEnd();
//textfields.replaceRange("",start,end);
textfields.setText(ss);
ss = (String)contents.getTransferData(flavor);
int n=textfields.getCaretPosition();
textfields.insert(ss,n);
}catch(Exception ee){
// TODO: handle exception
}
}
}*///未實現剪貼板粘貼功能
// end actionPerformed()
// end class Calculator
}
public static void main(String args[]) {
Calculator cal = new Calculator();
}
}
Ⅸ 用java程序編寫一個計算器
給你一個參考,希望不要被網路吞了當晚餐
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
//計算器面板
private JFrame f = new JFrame("Calculator");
//輸入面扳
private JPanel inputPanel = new JPanel();
//加減乘除面板
private JPanel operationPanel = new JPanel();
//數字面板
private JPanel buttonsPanel = new JPanel();
//輸入數據文本框
private JTextField input = new JTextField(20);
//退格鍵
private JButton backspace = new JButton("BackSpace");
//清空
private JButton CE = new JButton("CE ");
//刪除
private JButton C = new JButton("C ");
//四則運算符號鍵
private JButton add = new JButton("+");
private JButton sub = new JButton("-");
private JButton mul = new JButton("*");
private JButton div = new JButton("/");
//小數點
private JButton decimal = new JButton(".");
//等號
private JButton equal = new JButton("=");
//數字鍵
private JButton zero = new JButton("0");
private JButton one = new JButton("1");
private JButton two = new JButton("2");
private JButton three = new JButton("3");
private JButton four = new JButton("4");
private JButton five = new JButton("5");
private JButton six = new JButton("6");
private JButton seven = new JButton("7");
private JButton eight = new JButton("8");
private JButton nine = new JButton("9");
private String num1 = "";//保存第一個運算數字
private String operator = "";//保存運算符號
public static void main(String[] args) {
new Calculator();//new計算器實例
}
public Calculator(){
//添加組件,布局
inputPanel.add(input);
f.add(inputPanel, BorderLayout.NORTH);
operationPanel.add(backspace);
operationPanel.add(CE);
operationPanel.add(C);
f.add(operationPanel, BorderLayout.CENTER);
buttonsPanel.add(add);
buttonsPanel.add(sub);
buttonsPanel.add(mul);
buttonsPanel.add(div);
buttonsPanel.add(one);
buttonsPanel.add(two);
buttonsPanel.add(three);
buttonsPanel.add(zero);
buttonsPanel.add(four);
buttonsPanel.add(five);
buttonsPanel.add(six);
buttonsPanel.add(decimal);
buttonsPanel.add(seven);
buttonsPanel.add(eight);
buttonsPanel.add(nine);
buttonsPanel.add(equal);
buttonsPanel.setLayout(new GridLayout(4, 4));
f.add(buttonsPanel, BorderLayout.SOUTH);
//注冊各個組件監聽事件
backspace.addMouseListener(new OperationMouseListener());
CE.addMouseListener(new OperationMouseListener());
C.addMouseListener(new OperationMouseListener());
decimal.addMouseListener(new OperationMouseListener());
equal.addMouseListener(new OperationMouseListener());
//注冊四則運算監聽
add.addMouseListener(new CalcMouseListener());
sub.addMouseListener(new CalcMouseListener());
mul.addMouseListener(new CalcMouseListener());
div.addMouseListener(new CalcMouseListener());
//注冊數字監聽事件
zero.addMouseListener(new NumberMouseListener());
one.addMouseListener(new NumberMouseListener());
two.addMouseListener(new NumberMouseListener());
three.addMouseListener(new NumberMouseListener());
four.addMouseListener(new NumberMouseListener());
five.addMouseListener(new NumberMouseListener());
six.addMouseListener(new NumberMouseListener());
seven.addMouseListener(new NumberMouseListener());
eight.addMouseListener(new NumberMouseListener());
nine.addMouseListener(new NumberMouseListener());
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class NumberMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(input.getText().trim().equals("0")){//如果文本框已經是0,結果還是0
input.setText(((JButton)e.getSource()).getText().trim());
}else{//否則的話,把0添加到後面,譬如文本框是1,結果就為10
input.setText(input.getText().concat(((JButton)e.getSource()).getText().trim()));
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class CalcMouseListener implements MouseListener{
//如果輸入的是運算符號,保存第一個結果和運算符號
public void mouseClicked(MouseEvent e) {
num1 = input.getText().trim();input.setText("");
operator = ((JButton)e.getSource()).getText().trim();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class OperationMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(e.getSource() == backspace){//退格鍵,刪除一個直到沒有字元刪除
String inputText = input.getText();
if(inputText.length() > 0){
input.setText(inputText.substring(0, inputText.length() - 1));
}
}else if(e.getSource() == C){
input.setText("0");//C,清空所有運算數字和符號
num1 = "";
}else if(e.getSource() == CE){
input.setText("0");//CE-->將文本框置為0
}else if(e.getSource() == decimal){
String text = input.getText().trim();
//如果按了小數點,如果文本框已經有小數點,不做任何操作,否則在結果後面加上小數點
if(text.indexOf(".") == -1){
input.setText(text.concat("."));
}
}else if(e.getSource() == equal){
//如果是等號
if(!operator.trim().equals("")){
if(!input.getText().trim().equals("")){
double result = 0D;
if(operator.equals("+")){//執行加法運算
result = Double.parseDouble(num1) + Double.parseDouble(input.getText().trim());
}else if(operator.equals("-")){//減法運算
result = Double.parseDouble(num1) - Double.parseDouble(input.getText().trim());
}else if(operator.equals("*")){//乘法運算
result = Double.parseDouble(num1) * Double.parseDouble(input.getText().trim());
}else if(operator.equals("/")){//除法運算
result = Double.parseDouble(num1) / Double.parseDouble(input.getText().trim());
}
//格式化最終結果,保留兩位小數點
input.setText(new DecimalFormat("0.00").format(result));
}
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
Ⅹ 用純WIN32編寫計算器(界面如同WINDOWS上的計算器)其計算的演算法是什麼
你是指VC編程中的win32??
那不是很簡單嘛直接乘除不就行了。
a=b*c;(b與c由接受到的數據賦值,a為得數,輸出就行了嘛。