本文目錄一覽:
JAVA中long型代碼,支持大整數的四則運算
public long add(long a , long b){
BigInteger bigIntA = new BigInteger(a + “”);
BigInteger bigIntB = new BigInteger(b + “”);
return bigIntA.add(bigIntB).longValue;
}public long subtract(long a , long b){
BigInteger bigIntA = new BigInteger(a + “”);
BigInteger bigIntB = new BigInteger(b + “”);
return bigIntA.subtract(bigIntB).longValue;
}public long multiply(long a , long b){
BigInteger bigIntA = new BigInteger(a + “”);
BigInteger bigIntB = new BigInteger(b + “”);
return bigIntA.multiply(bigIntB).longValue;
}public long divide(long a , long b){
BigInteger bigIntA = new BigInteger(a + “”);
BigInteger bigIntB = new BigInteger(b + “”);
return bigIntA.divide(bigIntB).longValue;
}
運用JAVA中大數類實現大數的四則運算
import java.math.BigInteger;
public class BigIntegerGet {
public String getAdd(String Str1,String Str2){
String Str3=new String();
BigInteger BigInt1=new BigInteger(Str1);
BigInteger BigInt2=new BigInteger(Str2);
BigInt1=BigInt1.add(BigInt2);
Str3=BigInt1.toString();
return Str3;
}
public String getSubtract(String Str1,String Str2){
String Str3=new String();
BigInteger BigInt1=new BigInteger(Str1);
BigInteger BigInt2=new BigInteger(Str2);
BigInt1=BigInt1.subtract(BigInt2);
Str3=BigInt1.toString();
return Str3;
}
public String getMultiply(String Str1,String Str2){
String Str3=new String();
BigInteger BigInt1=new BigInteger(Str1);
BigInteger BigInt2=new BigInteger(Str2);
BigInt1=BigInt1.multiply(BigInt2);
Str3=BigInt1.toString();
return Str3;
}
public String getDivide(String Str1,String Str2){
String Str3=new String();
BigInteger BigInt1=new BigInteger(Str1);
BigInteger BigInt2=new BigInteger(Str2);
BigInt1=BigInt1.divide(BigInt2);
Str3=BigInt1.toString();
return Str3;
}
}
編寫一個實現四則運算的JAVA程序
import java.text.DecimalFormat;
import java.util.Scanner;
public class Zhidao {
public static void main(String[] args) {
String condition = “”;
Zhidao zhidao = new Zhidao();
do{
Scanner scanner = new Scanner(System.in);
try{
System.out.print(“請輸入第一個數:”);
double x = scanner.nextDouble();
System.out.print(“請輸入第二個數:”);
double y = scanner.nextDouble();
System.out.print(“請輸入運算符:”);
String s = scanner.next();
char z = s.charAt(0);
zhidao.yunsuan(x, y, z);
}catch(Exception e){
System.out.println(“請輸入正確的數據!”);
}
System.out.print(“是否繼續?continue:繼續,任意字元:結束”);
condition = scanner.next();
}while(“continue”.equals(condition));
}
public static void yunsuan(double x,double y,Character z){
DecimalFormat r=new DecimalFormat();
r.applyPattern(“#0.00”);
if(z.equals(‘+’)){
System.out.println(x+”+”+y+”=” + r.format((x+y)));
} else if(z.equals(‘-‘)){
System.out.println(x+”-“+y+”=” + r.format((x-y)));
} else if(z.equals(‘*’)){
System.out.println(x+”*”+y+”=” + r.format((x*y)));
} else if(z.equals(‘/’)){
if(y==0){
System.out.println(“被除數不能為0”);
} else{
System.out.println(x+”/”+y+”=” + r.format((x/y)));
}
}else{
System.out.println(“無法識別改運算符”);
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/300971.html