我想将用户的输入作为Big-Integer并将其操作为For循环
BigInteger i;
for(BigInteger i=0; i<=100000; i++) {
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
但它不会起作用
有谁能够帮我.
pol*_*nts 47
您可以使用以下语法:
BigInteger i = BigInteger.valueOf(100000L); // long i = 100000L;
i.compareTo(BigInteger.ONE) > 0 // i > 1
i = i.subtract(BigInteger.ONE) // i = i - 1
Run Code Online (Sandbox Code Playgroud)
所以这是将它组合在一起的一个例子:
for (BigInteger bi = BigInteger.valueOf(5);
bi.compareTo(BigInteger.ZERO) > 0;
bi = bi.subtract(BigInteger.ONE)) {
System.out.println(bi);
}
// prints "5", "4", "3", "2", "1"
Run Code Online (Sandbox Code Playgroud)
请注意,使用BigInteger循环索引非常不典型.long通常就足够了.
compareTo成语从文档:
优先于每个六个布尔比较运算符个体的方法(提供此方法是
<,==,>,>=,!=,<=).建议用于执行这些比较的习惯用法是:( ),其中六个比较运算符之一.x.compareTo(y)<op>0<op>
换句话说,给定BigInteger x, y,这些是比较习语:
x.compareTo(y) < 0 // x < y
x.compareTo(y) <= 0 // x <= y
x.compareTo(y) != 0 // x != y
x.compareTo(y) == 0 // x == y
x.compareTo(y) > 0 // x > y
x.compareTo(y) >= 0 // x >= y
Run Code Online (Sandbox Code Playgroud)
这不是特定的BigInteger; 这适用于任何Comparable<T>一般情况.
BigInteger,就像String,是一个不可变的对象.初学者倾向于犯下以下错误:
String s = " hello ";
s.trim(); // doesn't "work"!!!
BigInteger bi = BigInteger.valueOf(5);
bi.add(BigInteger.ONE); // doesn't "work"!!!
Run Code Online (Sandbox Code Playgroud)
由于它们是不可变的,因此这些方法不会改变它们被调用的对象,而是返回新对象,即这些操作的结果.因此,正确的用法是这样的:
s = s.trim();
bi = bi.add(BigInteger.ONE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33745 次 |
| 最近记录: |