问题:
乌托邦树每年经历2个生长周期。第一个生长周期发生在春季,当它的高度加倍时。第二个生长周期发生在夏季,其高度增加1米。现在,在春季开始时种植了新的乌托邦树苗。它的高度是1米。您可以在N个生长周期后找到树的高度吗?
输入格式第一行包含一个整数T,即测试用例的数量。T线跟随。每行包含一个整数N,表示该测试用例的周期数。
Constraints
1 <= T <= 10
0 <= N <= 60
输出格式对于每个测试用例,在N个循环后打印乌托邦树的高度。
//最后,希望如此..什么问题在说..
初始值是1 ..如果发生春天,它的值将加倍..意思是..它的值将被乘以2。但是如果夏天发生,则它的值将增加1 ...
如果我输入:
2 //here 2 is the number of question..
0
1
因此,输出必须为:
1
2
另一个例子,
输出样本:
2
3
4
因此,输入样本将为:
6
7
希望如此。您了解问题的所在,现在我们需要将程序编入Java...。
好的,我进一步为此做了一个程序。
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
当我碰到这里..它将第二个问题添加到我的输出中。
如果我输入为:
2
3
4
因此,输出必须假定为:
6
7
哪个是正确的!!
但是我的程序将输出显示为:
6
27 //which is incorrect..becoz it adds the sum of above number :(
错误-int num = 1;
应该在父循环内部声明以刷新其值。
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
输出
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句