【发布时间】:2019-06-01 08:22:23
【问题描述】:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt(); //taking input number of elements in the array
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=scan.nextInt(); //taking input elements of the array
}
int count=0;
//start point
for(int i=0;i<n;i++){
//end point
for(int j=i;j<n;j++){
for(int k=i;k<=j;k++){
int sum=0;
sum+=a[k]; //calculating the sum of subarray
if(sum<0)
count++;
}
}
}
System.out.println(count); //printing the no of negative sums
}
}
这里有三个嵌套循环,第一个循环定义起始位置,第二个循环定义结束位置,第三个循环用于迭代子数组的元素并计算它们的总和,如果总和小于零,则增加计数。但是使用这段代码我得到了错误的答案。
【问题讨论】:
-
if (sum < 0) count++应该在k循环之后。并且sum应该在它之前声明。 -
什么错误答案?
-
@AndyTurner 考虑将其转换为答案。
-
对于 OP:可以使用一些日志记录或在调试器中逐步运行程序来轻松调试此问题。
-
@khelwood 我没有测试用例,因为我在编码网站上尝试过
标签: java arrays nested-loops