import java.lang.Math;
import java.math.BigInteger;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
int e1 = 20, d = 13;
BigInteger C = BigDecimal.valueOf(e1).toBigInteger();
BigInteger po = C.pow(d);
System.out.println("pow is:" + po);
int num = 11;
BigInteger x = po;
BigInteger n = BigDecimal.valueOf(num).toBigInteger();
BigInteger p, q, m;
System.out.println("x: " + x);
q=(x / n);
p=(q * n);
m=(x - p);
System.out.println("mod is:" + m);
}
}
我试过寻找一些与之相关但无法解决的答案。请有人告诉我这有什么不对。我将数据类型更改为整数,但电源功能不起作用。
这是我得到的错误:
error: bad operand types for binary operator '/'
q=(x/n);
^
first type: BigInteger
second type: BigInteger
Main.java:33: error: bad operand types for binary operator '*'
p=(q*n);
^
first type: BigInteger
second type: BigInteger
Main.java:34: error: bad operand types for binary operator '-'
m=(x-p);
^
first type: BigInteger
second type: BigInteger
3 errors
.
算术运算不适用于Java中的对象。然而,在BigInteger#add
中已经有类似BigInteger#divide
,BigInteger
等方法。而不是做
q=(x/n)
你会的
q = x.divide(n);
你不能在BigInteger
上使用运算符。他们不是像int
这样的原始人,他们是阶级。 Java没有运算符重载。
看看class documentation并使用相应的方法:
BigInteger first = BigInteger.ONE;
BigInteger second = BigInteger.TEN;
BigInteger addResult = first.add(second);
BigInteger subResult = first.subtract(second);
BigInteger multResult = first.multiply(second);
BigInteger divResult = first.divide(second);
您可以查找运算符的详细定义以及何时可以在Java Language Specification(JLS)中使用它们。
以下是相关部分的一些链接:
他们中的大多数都使用数值类型§4的概念,它由Integral Type和FloatingPointType组成:
积分类型为
byte
,short
,int
和long
,其值分别为8位,16位,32位和64位二进制补码整数,以及char
,其值为16位无符号整数代表UTF-16代码单元(§3.1)。浮点类型是
float
,其值包括32位IEEE 754浮点数,double
,其值包括64位IEEE 754浮点数。
此外,如果需要,Java可以将Integer
等包装类拆包到int
中,反之亦然。这会将拆箱转换§5.1.8添加到支持的操作数集中。
你创建的BigInteger
不必要地冗长而复杂:
// Yours
BigInteger C = BigDecimal.valueOf(e1).toBigInteger();
// Prefer this instead
BigInteger c = BigInteger.valueOf(e1);
如果可能的话,你应该更喜欢从String
到BigInteger
,从BigInteger
到String
。由于BigInteger
的目的是将它用于太大而无法用原语表示的数字:
// String -> BigInteger
String numberText = "10000000000000000000000000000000";
BigInteger number = new BigInteger(numberText);
// BigInteger -> String
BigInteger number = ...
String numberText = number.toString();
另外,请坚持Java命名约定。变量名应该是camelCase,所以c
而不是C
。
此外,更喜欢有意义的变量名称。像c
或d
这样的名称无助于任何人理解变量应该代表什么。
您不能在Java中的对象上执行诸如“*”,“/”,“+”之类的操作数,如果您需要这些操作,则需要像这样执行此操作
q = x.divide(n);
p=q.multiply(n);
m=x.subtract(p);