我是一般的java /编程新手,这是一个家庭作业。这就是我到目前为止:当我运行它时,我在n输入下得到2的幂。例如,如果n = 50,则输出为2 + 4 + 8 + 16 + 32 + = -2 我希望32后的+消失,我不知道如何正确地总结它。在这种情况下,我希望总和= 62。我尝试使用字符串构建器来取消最后两个字符,但这对我不起作用。
import java.util.Scanner;
public class Powers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Enter the upper limit: ");
n = scan.nextInt();
int sum = 0;
int power = 1;
for (int i = 0; i <= n; i++) {
power = 2 * power;
if (power < n && 0 < power) {
System.out.print(power + " + ");
}
sum = sum + power;
}
System.out.println(" = " + sum);
}
}
答案 0 :(得分:0)
这里有多个问题:
50
,则执行1到2 ^ 50之间所有值的总和,这就是结果为负的原因,因为总和大于int
可以保留的最大数量。关于如何打破循环的问题,有break
; - )
您的打印件始终输出+
,这就是您输出中+ =
的原因。将输出更改为以下内容:
if (power < n && 0 < power) {
if (i != 0) {
System.out.print(" + ");
}
System.out.print(power);
}
答案 1 :(得分:0)
我在代码中添加了一些功能。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Type number:");
Scanner scanner = new Scanner(System.in);
int n = 0;
while (n == 0) { // to ask again if "n" is zero.
n = scanner.nextInt();
}
if (n != 0) {
scanner.close(); // to prevent resource leak
int sum = 0;
int power = 1;
for (int i = 0; i < n; i++) {
power *= 2;
sum += power;
System.out.print(power + " ");
if (sum + power * 2 < 0 | i == n - 1) {
// Should we step to the next iteration?
// If next "sum" will be bigger than the max value for
// integers
// or if this iteration is the last - it will type "sum",
// break "for" cycle and go the next line of code after
// "for" cycle.
// So in this case System.out.print("+ "); won't be
// executed.
System.out.print("= " + sum);
break;
}
System.out.print("+ ");
}
}
}
}