没有得到以下代码的实际输出:

时间:2017-02-25 07:46:07

标签: java netbeans

import java.util.*;
public class Main {

       Scanner input = new Scanner (System.in);
       int n = 0, tn = 0, time = 0;int sum=0;
       int t = input.nextInt(); //no. of test cases
       for (int i =0; i<t; i++)
       {  
          n = input.nextInt();//no. of timings           
          for (int j = 0; j<n; j++)
           {   
               tn = input.nextInt(); //individual time

               sum=0;
               sum+=tn;
               sum*=2;
           }
          System.out.println(t+". "+sum);
        }

    }
}

My output

output I am supposed to get

谁能告诉我哪里出错了?

1 个答案:

答案 0 :(得分:1)

1。)您在每次sum=0时都会设置新输入,因此您上次丢失之前的值

sum=30
sum= 30*2 = 60

完成第一个案例输入后重置sum=0

2。)您需要在汇总所有值后进行乘法运算,以便在得到所有sum值的individual time时进行乘法

for (int i = 0; i < t; i++) {
    n = input.nextInt();// no. of timings
    for (int j = 0; j < n; j++) {
        tn = input.nextInt(); // individual time
        // add all values first
        sum += tn;
    }
    // multiply the total of values with 2
    System.out.println(i + ". " + (sum * 2));

    // now set sum=0 for next case
    sum = 0;
}

测试用例输出:

2
3
10
20
30
2. 120 // output of first case
2
100
50
2. 300 // output of second case