當前位置:首頁 » 操作系統 » 計算器程序源碼

計算器程序源碼

發布時間: 2024-12-03 12:58:13

㈠ 用java編寫的科學計算器源代碼

以下是一個簡單的用Java編寫的科學計算器的源代碼示例:

java

import java.util.Scanner;

public class ScientificCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Scientific Calculator!");

System.out.println("Enter 'add', 'subtract', 'multiply', 'divide', 'sin', 'cos', 'tan', 'log', 'exp', 'sqrt', or 'quit' to exit.");

while (true) {

System.out.print("Enter operation (e.g., add 2 3): ");

String operation = scanner.nextLine();

if (operation.equalsIgnoreCase("quit")) {

break;

}

String[] parts = operation.split(" ");

double num1 = Double.parseDouble(parts[1]);

double num2 = Double.parseDouble(parts[2]);

switch (parts[0].toLowerCase()) {

case "add":

System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));

break;

case "subtract":

System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));

break;

case "multiply":

System.out.println(num1 + " * " + num2 + " = " + (num1 * num2));

break;

case "divide":

if (num2 != 0) {

System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));

} else {

System.out.println("Error: Division by zero is not allowed.");

}

break;

case "sin":

System.out.println("sin(" + num1 + ") = " + Math.sin(Math.toRadians(num1)));

break;

case "cos":

System.out.println("cos(" + num1 + ") = " + Math.cos(Math.toRadians(num1)));

break;

case "tan":

System.out.println("tan(" + num1 + ") = " + Math.tan(Math.toRadians(num1)));

break;

case "log":

System.out.println("log(" + num1 + ") = " + Math.log10(num1));

break;

case "exp":

System.out.println("exp(" + num1 + ") = " + Math.exp(num1));

break;

case "sqrt":

if (num1 >= 0) {

System.out.println("sqrt(" + num1 + ") = " + Math.sqrt(num1));

} else {

System.out.println("Error: Cannot calculate the square root of a negative number.");

}

break;

default:

System.out.println("Error: Invalid operation.");

break;

}

}

scanner.close();

System.out.println("Goodbye!");

}

}

這個科學計算器支持基本的四則運算(加、減、乘、除)以及一些科學運算(正弦、餘弦、正切、對數、指數和平方根)。用戶可以通過輸入相應的操作和兩個數字來執行計算。例如,輸入“add 2 3”將計算2加3的結果。

代碼首先導入了`Scanner`類,用於從用戶處獲取輸入。然後,在`main`方法中,創建了一個`Scanner`對象,用於讀取用戶的輸入。程序通過一個無限循環來持續接收用戶的輸入,直到用戶輸入“quit”為止。

在循環中,程序首先提示用戶輸入一個操作,然後讀取用戶的輸入並將其分割為多個部分。接著,程序將第二個和第三個部分轉換為`double`類型的數字,並根據第一個部分(即操作)執行相應的計算。

程序使用`switch`語句來根據用戶輸入的操作執行相應的計算。對於基本的四則運算,程序直接執行相應的計算並輸出結果。對於科學運算,程序使用了Java的`Math`類中的相應方法。例如,對於正弦運算,程序使用了`Math.sin`方法,並將角度轉換為弧度作為參數傳遞給它。

如果用戶輸入了無效的操作或無效

㈡ java 寫的計算器源代碼只實現加減乘除四則運算即可

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
public class calculator
{
String str1="0"; //運算數1 初值一定為0 為了程序的安全
String str2="0"; //運算數2
String fh="+"; //運算符
String jg="";//結果
//狀態開關 重要
int k1=1;//開關1 用於選擇輸入方向 將要寫入str2或 str2
int k2=1;//開關2 符號鍵 次數 k2>1說明進行的是2+3-9+8 這樣的多符號運算
int k3=1;//開關3 str1 是否可以被清0 ==1時可以 !=1時不能被清0
int k4=1;//開關4 str2 同上
int k5=1;//開關5 控制小數點可否被錄入 ==1時可以 !=1 輸入的小數點被丟掉
JButton jicunqi; //寄存器 記錄 是否連續按下符號鍵
Vector vt=new Vector(20,10);
JFrame frame=new JFrame("sunshine---計算器");
JTextField jg_TextField=new JTextField(jg,20);//20列
JButton clear_Button=new JButton("清除");
JButton button0=new JButton("0");
JButton button1=new JButton("1");
JButton button2=new JButton("2");
JButton button3=new JButton("3");
JButton button4=new JButton("4");
JButton button5=new JButton("5");
JButton button6=new JButton("6");
JButton button7=new JButton("7");
JButton button8=new JButton("8");
JButton button9=new JButton("9");
JButton button_Dian=new JButton(".");
JButton button_jia=new JButton("+");
JButton button_jian=new JButton("-");
JButton button_cheng=new JButton("*");
JButton button_chu=new JButton("/");
JButton button_dy=new JButton("=");
public static void main(String[] args)
{
calculator calculator=new calculator();
}
calculator()
{
jg_TextField.setHorizontalAlignment(JTextField.RIGHT );//文本框 右對齊
JPanel pan=new JPanel();
pan.setLayout(new GridLayout(4,4,5,5));//四行四列 邊距為5像素
pan.add(button7);
pan.add(button8);
pan.add(button9);
pan.add(button_chu);
pan.add(button4);
pan.add(button5);
pan.add(button6);
pan.add(button_cheng);
pan.add(button1);
pan.add(button2);
pan.add(button3);
pan.add(button_jian);
pan.add(button0);
pan.add(button_Dian);
pan.add(button_dy);
pan.add(button_jia);
pan.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));//pan對象的邊距
JPanel pan2=new JPanel();
pan2.add(jg_TextField);
JPanel pan3=new JPanel(); //為什麼要 多此一句呢? 因為我不會設置 按鈕的大小
pan3.setLayout(new FlowLayout());
pan3.add(clear_Button);
//clear_Button.setSize(10,10);//設置清零按鈕的大小 嗎的 不好使 !!
frame.setLocation(300, 200); //主窗口 出現在位置
frame.setResizable(false); //不能調大小
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(pan2,BorderLayout.NORTH);
frame.getContentPane().add(pan,BorderLayout.CENTER);
frame.getContentPane().add(pan3,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
//以上是 控制項 和 布局
//下面是事件處理 程 序
//--------------- 數 字 鍵 ----------------
class JianTing implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String ss=((JButton)e.getSource()).getText();
jicunqi=(JButton)e.getSource();
vt.add(jicunqi);
if (k1==1)
{
if(k3==1)
{
str1="";
k5=1;//還原開關k5狀態
}
str1=str1+ss;
//k2=1;
k3=k3+1;
//System.out.println(str1);
jg_TextField.setText(str1);//顯示
}
else if(k1==2)
{
if (k4==1)
{
str2="";
k5=1; //還原開關k5狀態
}
str2=str2+ss;
//k2=2;
k4=k4+1;
///////////////測試////////////////
jg_TextField.setText(str2);
}
}
}

//--------符 號-----------
class JianTing_fh implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String ss2=((JButton)e.getSource()).getText();
jicunqi=(JButton)e.getSource();
vt.add(jicunqi);
if(k2==1)
{
k1=2;//開關 k1 為1時,向數1寫 為2時,向數2寫
k5=1;
fh=ss2;
k2=k2+1;//按符號鍵的次數
}
else
{
int a=vt.size();
JButton c=(JButton)vt.get(a-2); if(!(c.getText().equals("+"))&&!(c.getText().equals("-"))&&!(c.getText().equals("*"))&&!(c.getText().equals("/")))
{
yuns();
str1=jg;
k1=2;//開關 k1 為1時,向數1寫 為2時,向數2寫
k5=1;
k4=1;
fh=ss2;
} k2=k2+1;
}
}
}
//--------清除-------
class JianTing_clear implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jicunqi=(JButton)e.getSource();
vt.add(jicunqi);
k5=1;
k2=1;
k1=1;
k3=1;
k4=1;
str1="0";
str2="0";
fh="";
jg="";
jg_TextField.setText(jg);
vt.clear();
}
}
//----------------等 於 ---------------------
class JianTing_dy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jicunqi=(JButton)e.getSource();
vt.add(jicunqi);
yuns();
k1=1; //還原開關k1狀態
//str1=jg;
k2=1;
k3=1;//還原開關k3狀態
k4=1; //還原開關k4狀態
str1=jg; //為7+5=12 +5=17 這種計算做准備
}
}
//----------------小數點 ---------------------
class JianTing_xiaos implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jicunqi=(JButton)e.getSource();
vt.add(jicunqi);
if(k5==1)
{
String ss2=((JButton)e.getSource()).getText();
if (k1==1)
{
if(k3==1)
{
str1="";
k5=1; //還原開關k5狀態
}
str1=str1+ss2;
//k2=1;
k3=k3+1;
//System.out.println(str1);
jg_TextField.setText(str1);//顯示
}
else if(k1==2)
{
if (k4==1)
{
str2="";
k5=1; //還原開關k5狀態
}
str2=str2+ss2;
//k2=2;
k4=k4+1;
///////////////測試////////////////
jg_TextField.setText(str2);
}
}
k5=k5+1;
}
}
//注冊 監聽器
JianTing_dy jt_dy=new JianTing_dy();
JianTing jt= new JianTing();//臨聽數字鍵
JianTing_fh jt_fh= new JianTing_fh();//臨 聽符 號鍵
JianTing_clear jt_c=new JianTing_clear(); //清除鍵
JianTing_xiaos jt_xs=new JianTing_xiaos();// 小數點 鍵
button7.addActionListener(jt);
button8.addActionListener(jt);
button9.addActionListener(jt);
button_chu.addActionListener(jt_fh);
button4.addActionListener(jt);
button5.addActionListener(jt);
button6.addActionListener(jt);
button_cheng.addActionListener(jt_fh);
button1.addActionListener(jt);
button2.addActionListener(jt);
button3.addActionListener(jt);
button_jian.addActionListener(jt_fh);
button0.addActionListener(jt);
button_Dian.addActionListener(jt_xs);
button_dy.addActionListener(jt_dy);
button_jia.addActionListener(jt_fh);
clear_Button.addActionListener(jt_c);
//關閉事件處理程序
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
//---------------計 算------------------
public void yuns()
{
double a2,b2;//運算數1,2
String c=fh;// 運算符
double jg2=0 ;//結果
if (c.equals(""))
{
//System.out.println("請輸入運算符");
jg_TextField.setText("請輸入運算符");
}
else
{
System.out.println("str1:"+str1);//調試時 使 用
System.out.println("str2:"+str2);//調試時 使 用
System.out.println("運算符:"+fh);//調試時 使 用
if (str1.equals(".")) //字元串 "." 轉換成double型數據時 會出錯 所以手工轉
str1="0.0";
if (str2.equals("."))
str2="0.0";
a2=Double.valueOf(str1).doubleValue();
b2=Double.valueOf(str2).doubleValue();
System.out.println("double型的a2:"+a2); //調試時 使 用
System.out.println("double型的b2:"+b2); //調試時 使 用
if (c.equals("+"))
{
jg2=a2+b2;
}
if (c.equals("-"))
{
jg2=a2-b2;
}
if (c.equals("*"))
{
jg2=a2*b2;
}
if (c.equals("/"))
{
if(b2==0)
{
jg2=0;//0000000000000 by 0 cu!
}
else
{
jg2=a2/b2;
}
}
System.out.println("double型a2"+fh+"b2結果:"+jg2);
System.out.println();
jg=((new Double(jg2)).toString());
jg_TextField.setText(jg);
}
}
}

㈢ java計算器源代碼

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
initComponents();
}

private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
num1 = new javax.swing.JTextField();
num2 = new javax.swing.JTextField();
result = new javax.swing.JTextField();
addBtn = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Num1:");

jLabel2.setText("Num2:");

jLabel3.setText("Num3:");

addBtn.setText("Add");
addBtn.addActionListener(new jisuanAC());

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addBtn)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(31, 31, 31)
.addComponent(num1, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(result)
.addComponent(num2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGap(168, 168, 168))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(61, 61, 61)
.addComponent(addBtn)
.addContainerGap(81, Short.MAX_VALUE))
);

jMenu1.setText("Operation");

jMenu3.setText("Add");
jMenu1.add(jMenu3);

jMenuBar1.add(jMenu1);

jMenu2.setText("Exit");
jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private class jisuanAC implements ActionListener
{

public void actionPerformed(ActionEvent e) {
if(e.getSource()== addBtn)
{
int number1 = Integer.parseInt(num1.getText());
int number2 = Integer.parseInt(num2.getText());
int rs = number1 + number2;
result.setText(String.valueOf(rs));

}
}

}

// Variables declaration - do not modify
private javax.swing.JButton addBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField result;

}

這是只有一個加法的例子!希望幫到你

㈣ 鐢╦ava緙栧緱璁$畻鍣ㄧ▼搴忚蔣浠跺拰婧愪唬鐮

java璁$畻鍣ㄦ簮紼嬪簭
java璁$畻鍣

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class calculation extends JFrame
{public calculation() /*鏋勯犳柟娉*/
{super("璁℃暟鍣");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initTextPanel(); /*鏂囨湰妗*/
initControlPanel(); /*鎺у埗閿*/
initKeyPanel(); /*鏁板瓧鍜岃繍綆楃*/
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(TextPanel,BorderLayout.NORTH);
pane.add(ControlPanel,BorderLayout.CENTER);
pane.add(KeyPanel,BorderLayout.SOUTH);
pack();
try
{UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception ex)
{;} /璁╅敭*璁劇疆Windons瑙傛劅*/
SwingUtilities.updateComponentTreeUI(this);
setResizable(false);
setVisible(true);
}

private void initTextPanel() /*璁劇疆鏂囨湰妗*/
{ TextPanel=new JPanel();
TextPanel.setLayout(new FlowLayout());
Resultarea =new JTextField("0",25);
Resultarea.setEditable(false); /*璁劇疆涓嶅彲緙栬緫*/
Color color=Color.white;
Resultarea.setBackground(color); /*棰滆壊*/
Resultarea.setHorizontalAlignment(JTextField.RIGHT); /*璁炬墥婊戞壆緗鏄劇ず浣嶇疆*/
TextPanel.add(Resultarea);
}

private void initControlPanel() /*璁劇疆鎺у埗閿鏄ョ伓*/
{ControlPanel=new JPanel();
ControlPanel.setLayout(new GridLayout(1,3,4,4));
JButton b1=new JButton("Backspace"); /*Backspace閿*/
b1.setFont(font1);
b1.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e)
{String s1=Resultarea.getText();
int l=s1.length();
Resultarea.setText(s1.substring(0 ,l-1));
}
});

ControlPanel.add(b1);
JButton b2=new JButton("CE"); /*CE閿*/
b2.setFont(font1);
b2.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e)
{Resultarea.setText("0");
isNew=true;
}
});
ControlPanel.add(b2);

JButton b3=new JButton("C"); /*C閿*/
b3.setFont(font1);
b3.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent e)
{Resultarea.setText("0");
pnum="";
operation="";
isNew=true;
}
});
ControlPanel.add(b3);
}

private void initKeyPanel() /*璁劇疆鏁板瓧閿鍜岃繍綆楃﹂敭*/
{String key[] = {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};
KeyPanel = new JPanel();
KeyPanel.setLayout(new GridLayout(4,5,4,4));
for(int i=0;i<20;i++)
{String label = key[i];
JButton b = new JButton(label);
b.setActionCommand(key[i]);
b.setFont(font2);
KeyPanel.add(b);
b.addActionListener(new ActionListener() /*鏃犲悕鐩戝惉鍣*/
{public void actionPerformed(ActionEvent e)
{Key_actionPerformed(e);
}
});
}
}
public void Key_actionPerformed(ActionEvent e) /*鏁板瓧閿鍜岃繍綆楃﹂敭鏃犲悕鐩戝惉鍣*/
{String s=(e.getActionCommand());
String st=Resultarea.getText();
if(s.equals("0")) /*杈撳叆鏁頒負0*/
{if(st.equals("0"))
return;
else
{if(!isNew)
Resultarea.setText(st+"0");
else
Resultarea.setText("0");
}
isNew=false;
return;
}

if(s.equals("+/-")) /*杈撳叆鏁頒負+/-*/
{double k=Double.parseDouble(st);
{if(k!=0)
display(-k);

}
return;
}

if(s.equals("1")||s.equals("2")||s.equals("3")||s.equals("4")||s.equals("5")||s.equals("6")||s.equals("7")||s.equals("8")||s.equals("9")) /*杈撳叆1-9*/
{if(!isNew)
Resultarea.setText(st+s);
else
{ Resultarea.setText(s);
isNew=false;
}
return;
}

if(s.equals(".")) /*杈撳叆灝忔暟鐐*/
{if(Resultarea.getText().indexOf(".")==-1) /*涓嶅瓨鍦ㄥ皬鏁扮偣*/
{if(isNew)
{Resultarea.setText("0.");
isNew=false;
}
else
Resultarea.setText(st+".");
}
return;
}

isNew=true; /*鎸変笅榪愮畻絎︼紝杈撳叆鏂扮殑鏁*/
if(s.equals("="))
{compute(s);
operation="";
}
else
{if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) /*浜岀洰榪愮畻絎﹀彿*/
{if(operation.equals(""))
{pnum=Resultarea.getText();
operation=s;
}
else
compute(s);
}
else /*涓鐩榪愮畻*/
{Count count1=new Count(Double.parseDouble(st));
if(s.equals("sqrt"))
{
display(count1.sqrt());

}
else
{if(s.equals("1/x"))
{if(st.equals("0"))
{Resultarea.setText("闄ゆ暟涓嶈兘涓0.");
operation="";
pnum="";
}
else
display(count1.reciprocal()); /*奼傚掓暟*/
}
else
display(Double.parseDouble(st)/100); /*杈撳叆%錛屼嬌褰撳墠鏄劇ず鐨勫奸櫎浜100*/
}
}
}
}

private void compute(String s)
{if(s.equals("="))
{if(operation.equals(""))
return;
}
double data1=Double.parseDouble(pnum);
double data2=Double.parseDouble(Resultarea.getText());
Count count2=new Count(data1,data2); /*鍔犲噺涔橀櫎璁$畻*/
if(operation.equals("+"))
display((count2.plus()));
else
{if(operation.equals("-"))
display((count2.minus()));
else
{if(operation.equals("*"))
display((count2.multiply()));
else
if(operation.equals("/"))
{if(data2==0)
{Resultarea.setText("闄ゆ暟涓嶈兘涓0");
operation="";
pnum="";
return;
}
else
display((count2.divide()));
}
}
}
operation=""; /*絎﹀彿涓哄綋鍓嶇*/
pnum=Resultarea.getText();/*榪愮畻鏁頒負褰撳墠鏂囨湰鏁*/
}

public void display(double result) /*鏄劇ず杈撳嚭鏂規硶*/
{int a=(int)result;
if(a==result)
Resultarea.setText(String.valueOf(a));
else
Resultarea.setText(String.valueOf(result));
if(Resultarea.getText().equals("NaN"))
Resultarea.setText("杈撳叆鍑芥暟鏃犳晥");
}

private JPanel TextPanel; /*鏂囨湰妗嗘夋澘*/
private JTextField Resultarea; /*鏂囨湰妗*/
private JPanel ControlPanel; /*鎺у埗閿閿闈㈡澘*/
private JPanel KeyPanel; /*鏁板瓧閿鍜岃繍綆楃﹂敭闈㈡澘*/
private Font font1=new Font("Dialog",0, 10); /*鎺у埗閿瀛椾綋*/
private Font font2 = new Font("Dialog",0,10); /*鏁板瓧閿鍜岀﹀彿閿瀛椾綋*/
private String pnum=""; /*鍓嶆搷浣滄暟*/
private boolean isNew=true; /*鎺у埗鏄鍚︽槸鏂版暟*/
private String operation=""; /*榪愮畻絎*/
}

class tester /*嫻嬭瘯綾*/
{
public static void main(String[] args)
{
new calculation();
}
}

㈤ 用c語言程序設計一個簡單計算器,求其源代碼

#include <dos.h> /*DOS介面函數*/
#include <math.h> /*數學函數的定義*/
#include <conio.h> /*屏幕操作函數*/
#include <stdio.h> /*I/O函數*/
#include <stdlib.h> /*庫函數*/
#include <stdarg.h> /*變數長度參數表*/
#include <graphics.h> /*圖形函數*/
#include <string.h> /*字元串函數*/
#include <ctype.h> /*字元操作函數*/
#define UP 0x48 /*游標上移鍵*/
#define DOWN 0x50 /*游標下移鍵*/
#define LEFT 0x4b /*游標左移鍵*/
#define RIGHT 0x4d /*游標右移鍵*/
#define ENTER 0x0d /*回車鍵*/
void *rar; /*全局變數,保存游標圖象*/
struct palettetype palette; /*使用調色板信息*/
int GraphDriver; /* 圖形設備驅動*/
int GraphMode; /* 圖形模式值*/
int ErrorCode; /* 錯誤代碼*/
int MaxColors; /* 可用顏色的最大數值*/
int MaxX, MaxY; /* 屏幕的最大解析度*/
double AspectRatio; /* 屏幕的像素比*/
void drawboder(void); /*畫邊框函數*/
void initialize(void); /*初始化函數*/
void computer(void); /*計算器計算函數*/
void changetextstyle(int font, int direction, int charsize); /*改變文本樣式函數*/
void mwindow(char *header); /*窗口函數*/
int specialkey(void) ; /*獲取特殊鍵函數*/
int arrow(); /*設置箭頭游標函數*/
/*主函數*/
int main()
{
initialize();/* 設置系統進入圖形模式 */
computer(); /*運行計算器 */
closegraph();/*系統關閉圖形模式返迴文本模式*/
return(0); /*結束程序*/
}
/* 設置系統進入圖形模式 */
void initialize(void)
{
int xasp, yasp; /* 用於讀x和y方向縱橫比*/
GraphDriver = DETECT; /* 自動檢測顯示器*/
initgraph( &GraphDriver, &GraphMode, "" );
/*初始化圖形系統*/
ErrorCode = graphresult(); /*讀初始化結果*/
if( ErrorCode != grOk ) /*如果初始化時出現錯誤*/
{
printf("Graphics System Error: %s\n",
grapherrormsg( ErrorCode ) ); /*顯示錯誤代碼*/
exit( 1 ); /*退出*/
}
getpalette( &palette ); /* 讀面板信息*/
MaxColors = getmaxcolor() + 1; /* 讀取顏色的最大值*/
MaxX = getmaxx(); /* 讀屏幕尺寸 */
MaxY = getmaxy(); /* 讀屏幕尺寸 */
getaspectratio( &xasp, &yasp ); /* 拷貝縱橫比到變數中*/
AspectRatio = (double)xasp/(double)yasp;/* 計算縱橫比值*/
}
/*計算器函數*/
void computer(void)
{
struct viewporttype vp; /*定義視口類型變數*/
int color, height, width;
int x, y,x0,y0, i, j,v,m,n,act,flag=1;
float num1=0,num2=0,result; /*操作數和計算結果變數*/
char cnum[5],str2[20]={""},c,temp[20]={""};
char str1[]="1230.456+-789*/Qc=^%";/* 定義字元串在按鈕圖形上顯示的符號 */
mwindow( "Calculator" ); /* 顯示主窗口 */
color = 7; /*設置灰顏色值*/
getviewsettings( &vp ); /* 讀取當前窗口的大小*/
width=(vp.right+1)/10; /* 設置按鈕寬度 */
height=(vp.bottom-10)/10 ; /*設置按鈕高度 */
x = width /2; /*設置x的坐標值*/
y = height/2; /*設置y的坐標值*/
setfillstyle(SOLID_FILL, color+3);
bar( x+width*2, y, x+7*width, y+height );
/*畫一個二維矩形條顯示運算數和結果*/
setcolor( color+3 ); /*設置淡綠顏色邊框線*/
rectangle( x+width*2, y, x+7*width, y+height );
/*畫一個矩形邊框線*/
setcolor(RED); /*設置顏色為紅色*/
outtextxy(x+3*width,y+height/2,"0."); /*輸出字元串"0."*/
x =2*width-width/2; /*設置x的坐標值*/
y =2*height+height/2; /*設置y的坐標值*/
for( j=0 ; j<4 ; ++j ) /*畫按鈕*/
{
for( i=0 ; i<5 ; ++i )
{
setfillstyle(SOLID_FILL, color);
setcolor(RED);
bar( x, y, x+width, y+height ); /*畫一個矩形條*/
rectangle( x, y, x+width, y+height );
sprintf(str2,"%c",str1[j*5+i]);
/*將字元保存到str2中*/
outtextxy( x+(width/2), y+height/2, str2);
x =x+width+ (width / 2) ; /*移動列坐標*/
}
y +=(height/2)*3; /* 移動行坐標*/
x =2*width-width/2; /*復位列坐標*/
}
x0=2*width;
y0=3*height;
x=x0;
y=y0;
gotoxy(x,y); /*移動游標到x,y位置*/
arrow(); /*顯示游標*/
putimage(x,y,rar,XOR_PUT);
m=0;
n=0;
strcpy(str2,""); /*設置str2為空串*/
while((v=specialkey())!=45) /*當壓下Alt+x鍵結束程序,否則執行下面的循環*/
{
while((v=specialkey())!=ENTER) /*當壓下鍵不是回車時*/
{
putimage(x,y,rar,XOR_PUT); /*顯示游標圖象*/
if(v==RIGHT) /*右移箭頭時新位置計算*/
if(x>=x0+6*width)
/*如果右移,移到尾,則移動到最左邊字元位置*/
{
x=x0;
m=0;
}
else
{
x=x+width+width/2;
m++;
} /*否則,右移到下一個字元位置*/
if(v==LEFT) /*左移箭頭時新位置計算*/
if(x<=x0)
{
x=x0+6*width;
m=4;
} /*如果移到頭,再左移,則移動到最右邊字元位置*/
else
{
x=x-width-width/2;
m--;
} /*否則,左移到前一個字元位置*/
if(v==UP) /*上移箭頭時新位置計算*/
if(y<=y0)
{
y=y0+4*height+height/2;
n=3;
} /*如果移到頭,再上移,則移動到最下邊字元位置*/
else
{
y=y-height-height/2;
n--;
} /*否則,移到上邊一個字元位置*/
if(v==DOWN) /*下移箭頭時新位置計算*/
if(y>=7*height)
{
y=y0;
n=0;
} /*如果移到尾,再下移,則移動到最上邊字元位置*/
else
{
y=y+height+height/2;
n++;
} /*否則,移到下邊一個字元位置*/
putimage(x,y,rar,XOR_PUT); /*在新的位置顯示游標箭頭*/
}
c=str1[n*5+m]; /*將字元保存到變數c中*/
if(isdigit(c)||c=='.') /*判斷是否是數字或小數點*/
{
if(flag==-1) /*如果標志為-1,表明為負數*/
{
strcpy(str2,"-"); /*將負號連接到字元串中*/
flag=1;
} /*將標志值恢復為1*/
sprintf(temp,"%c",c); /*將字元保存到字元串變數temp中*/
strcat(str2,temp); /*將temp中的字元串連接到str2中*/
setfillstyle(SOLID_FILL,color+3);
bar(2*width+width/2,height/2,15*width/2,3*height/2);
outtextxy(5*width,height,str2); /*顯示字元串*/
}
if(c=='+')
{
num1=atof(str2); /*將第一個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=1; /*做計算加法標志值*/
setfillstyle(SOLID_FILL,color+3);
bar(2*width+width/2,height/2,15*width/2,3*height/2);
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='-')
{
if(strcmp(str2,"")==0) /*如果str2為空,說明是負號,而不是減號*/
flag=-1; /*設置負數標志*/
else
{
num1=atof(str2); /*將第二個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=2; /*做計算減法標志值*/
setfillstyle(SOLID_FILL,color+3);
bar(2*width+width/2,height/2,15*width/2,3*height/2); /*畫矩形*/
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
}
if(c=='*')
{
num1=atof(str2); /*將第二個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=3; /*做計算乘法標志值*/
setfillstyle(SOLID_FILL,color+3); bar(2*width+width/2,height/2,15*width/2,3*height/2);
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='/')
{
num1=atof(str2); /*將第二個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=4; /*做計算除法標志值*/
setfillstyle(SOLID_FILL,color+3);
bar(2*width+width/2,height/2,15*width/2,3*height/2);
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='^')
{
num1=atof(str2); /*將第二個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=5; /*做計算乘方標志值*/
setfillstyle(SOLID_FILL,color+3); /*設置用淡綠色實體填充*/
bar(2*width+width/2,height/2,15*width/2,3*height/2); /*畫矩形*/
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='%')
{
num1=atof(str2); /*將第二個操作數轉換為浮點數*/
strcpy(str2,""); /*將str2清空*/
act=6; /*做計算模運算乘方標志值*/
setfillstyle(SOLID_FILL,color+3); /*設置用淡綠色實體填充*/
bar(2*width+width/2,height/2,15*width/2,3*height/2); /*畫矩形*/
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='=')
{
num2=atof(str2); /*將第二個操作數轉換為浮點數*/
switch(act) /*根據運算符號計算*/
{
case 1:result=num1+num2;break; /*做加法*/
case 2:result=num1-num2;break; /*做減法*/
case 3:result=num1*num2;break; /*做乘法*/
case 4:result=num1/num2;break; /*做除法*/
case 5:result=pow(num1,num2);break; /*做x的y次方*/
case 6:result=fmod(num1,num2);break; /*做模運算*/
}
setfillstyle(SOLID_FILL,color+3); /*設置用淡綠色實體填充*/
bar(2*width+width/2,height/2,15*width/2,3*height/2); /*覆蓋結果區*/
sprintf(temp,"%f",result); /*將結果保存到temp中*/
outtextxy(5*width,height,temp); /*顯示結果*/
}
if(c=='c')
{
num1=0; /*將兩個操作數復位0,符號標志為1*/
num2=0;
flag=1;
strcpy(str2,""); /*將str2清空*/
setfillstyle(SOLID_FILL,color+3); /*設置用淡綠色實體填充*/
bar(2*width+width/2,height/2,15*width/2,3*height/2); /*覆蓋結果區*/
outtextxy(5*width,height,"0."); /*顯示字元串*/
}
if(c=='Q')exit(0); /*如果選擇了q回車,結束計算程序*/
}
putimage(x,y,rar,XOR_PUT); /*在退出之前消去游標箭頭*/
return; /*返回*/
}
/*窗口函數*/
void mwindow( char *header )
{
int height;
cleardevice(); /* 清除圖形屏幕 */
setcolor( MaxColors - 1 ); /* 設置當前顏色為白色*/
setviewport( 20, 20, MaxX/2, MaxY/2, 1 ); /* 設置視口大小 */
height = textheight( "H" ); /* 讀取基本文本大小 */
settextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );/*設置文本樣式*/
settextjustify( CENTER_TEXT, TOP_TEXT );/*設置字元排列方式*/
outtextxy( MaxX/4, 2, header ); /*輸出標題*/
setviewport( 20,20+height+4, MaxX/2+4, MaxY/2+20, 1 ); /*設置視口大小*/
drawboder(); /*畫邊框*/
}
void drawboder(void) /*畫邊框*/
{
struct viewporttype vp; /*定義視口類型變數*/
setcolor( MaxColors - 1 ); /*設置當前顏色為白色 */
setlinestyle( SOLID_LINE, 0, NORM_WIDTH );/*設置畫線方式*/
getviewsettings( &vp );/*將當前視口信息裝入vp所指的結構中*/
rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top ); /*畫矩形邊框*/
}
/*設計滑鼠圖形函數*/
int arrow()
{
int size;
int raw[]={4,4,4,8,6,8,14,16,16,16,8,6,8,4,4,4}; /*定義多邊形坐標*/
setfillstyle(SOLID_FILL,2); /*設置填充模式*/
fillpoly(8,raw); /*畫出一游標箭頭*/
size=imagesize(4,4,16,16); /*測試圖象大小*/
rar=malloc(size); /*分配內存區域*/
getimage(4,4,16,16,rar); /*存放游標箭頭圖象*/
putimage(4,4,rar,XOR_PUT); /*消去游標箭頭圖象*/
return 0;
}
/*按鍵函數*/
int specialkey(void)
{
int key;
while(bioskey(1)==0); /*等待鍵盤輸入*/
key=bioskey(0); /*鍵盤輸入*/
key=key&0xff? key&0xff:key>>8; /*只取特殊鍵的掃描值,其餘為0*/
return(key); /*返回鍵值*/
}

熱點內容
安卓上哪裡下大型游戲 發布:2024-12-23 15:10:58 瀏覽:189
明日之後目前適用於什麼配置 發布:2024-12-23 14:56:09 瀏覽:55
php全形半形 發布:2024-12-23 14:55:17 瀏覽:829
手機上傳助手 發布:2024-12-23 14:55:14 瀏覽:733
什麼樣的主機配置吃雞開全效 發布:2024-12-23 14:55:13 瀏覽:830
安卓我的世界114版本有什麼 發布:2024-12-23 14:42:17 瀏覽:711
vbox源碼 發布:2024-12-23 14:41:32 瀏覽:278
詩經是怎麼存儲 發布:2024-12-23 14:41:29 瀏覽:660
屏蔽視頻廣告腳本 發布:2024-12-23 14:41:24 瀏覽:420
php解析pdf 發布:2024-12-23 14:40:01 瀏覽:819