The question is to print the following series:
(a+(2^0)*b), ((a+(2^0)*b)+(a+(2^1)*b)), ((a+(2^0)*b)+(a+(2^1)*b)+(a+(2^2)*b)...+(a+(2^(n-1))*b))
The values of a,b,n and t are enterred by the user. 't' denotes the number of series that the user wants to calculate. For eg, if t=2, then the user can give two separate inputs of a,b and n and obtain two different series.
if t=2
a=0,b=2,n=10
and for second series-
a=5,b=3,n=5
Output should be:
2 6 14 30 62 126 254 510 1022 2046 (1st series)
8 14 26 50 98 (2nd series)
The program below is not showing the required output. Can someone please point out the mistakes?
import java.io.*;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
int s=0;
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
for(int j=0;j<n;j++)
{
s = s+(a+(2^j)*b);
System.out.print(s+" ");
}
}
in.close();
}
}
In your second inner loop your variable j is never updated (you are using i instead). Your problem may come from here.
在第二个循环中,它应该是j,而不是我喜欢的-> for(int j=0;j<n;j++)
j
instead of i
. And use java.lang.Math.pow;
Also u have typo in String []argh
=> String[] args
;
And i think int s
should be double s
import java.io.*;
import java.lang.*;
class Solution{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
double s=0;
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
for(int j=0 ; j<n ; i++)
{
s = s+(a+(java.lang.Math.pow(2, j))*b);
System.out.print(s+" ");
}
}
in.close();
}
}
^
doesn't mean power in java. ^
means bitwise XOR. Use java.lang.Math.pow
method instead.
内循环完成后,您应该使s = 0,系列才能重新开始
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.