我想找到系列中缺失的数字,所以我想到了一个简单的想法,为什么不将数组中系列中的所有数字相加并将其保存在一个变量中,然后通过公式 Sn= 计算系列总和n/2(a+l)
但是在计算系列总和时我遇到了一些错误。
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0; int total=0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length-1];
total = [n/2*(a+l)];
System.out.print("The missing number is "+(sum-total));
}}
total = [n/2*(a+l)]; ............................(1)
这就是我遇到错误的地方。
最佳答案
您可以使用以下逻辑,该逻辑更易于使用和理解
for(int i=0;i<ar.length-1;i++)
{
if(ar[i]!=ar[i+1]-1)
{
System.out.print("The missing number is "+(ar[i]+1)+"\n");
break;
}
}
关于java - 无法继续处理系列总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549177/