我是Java编程的初学者。我想求解表单的表达式 (a+2 0b(+(a+2 0 b+2 1 b(+........+(a+20b+...+2(n-1(b( 如果为每个查询以 a、b 和 n 的形式给出"q"查询,则打印与给定的 a、b 和 n 值对应的表达式值。这意味着样本输入:2 0 2
10
5 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();
}
}
这里的错误是在for
循环中声明a
、b
和n
,这意味着当循环结束时,变量也将丢失,垃圾回收器将处理它们。
解决这个问题真的很容易
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();
}