我是Java编程的初学者。我想解决形式的表达
(a + 20b)+(a + 20b + 21b)+ ... +(a + 20b + ... + 2(n-1)b),其中以形式提供“q”查询每个查询的a,b和n中,打印与给定的a,b和n值相对应的表达式值。那意味着
输入样例:
20 2 105 3 5
样本输出:
4072
196
我的代码是:

import java.util.Scanner;

public class Expression {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int q=in.nextInt();
    for(int i=0;i<q;i++){
        int a = in.nextInt();
        int b = in.nextInt();
        int n = in.nextInt();
    }
    int expr=a+b;                 //ERROR:a cannot be resolved to a variable
    for(int i = 0; i<n;i++)       //ERROR:n cannot be resolved to a variable
        expr+=a+Math.pow(2, i)*b; //ERROR:a and b cannot be resolved to variables
    System.out.print(expr);
    in.close();
}

}

最佳答案

这里的错误是在a循环中声明bnfor,这意味着当循环结束时,变量也将丢失,垃圾收集器将负责处理它们。

解决方案非常简单

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int q=in.nextInt();
    int a, b, n;               // Declare outside if you need them outside ;)
    for(int i=0;i<q;i++){
        a = in.nextInt();
        b = in.nextInt();
        n = in.nextInt();
    }
    int expr=a+b;              //ERROR:a cannot be resolved to a variable
    for(int i = 0; i<n;i++) {  //ERROR:n cannot be resolved to a variable
        expr+=a+(2*i)*b;       //ERROR:a and b cannot be resolved to variables
        System.out.print(expr);
    }
    in.close();
}

10-08 12:08