Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法继续进行序列和_Java - Fatal编程技术网

Java 无法继续进行序列和

Java 无法继续进行序列和,java,Java,我想在序列中找到缺失的数字,所以我想了一个简单的想法,为什么不将数组中所有串联的数字相加,并将其保存在一个变量中,然后通过公式Sn=n/2a+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; f

我想在序列中找到缺失的数字,所以我想了一个简单的想法,为什么不将数组中所有串联的数字相加,并将其保存在一个变量中,然后通过公式Sn=n/2a+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));

}}
总计=[n/2*a+l]。。。。。。。。。。。。。。。。。。。。。。。。。。。。一,

这就是我出错的地方

第一件事是总计=[n/2*a+l];[]在此上下文中是无效语法。我注意到的第二件事是,你计算总和的公式看起来很奇怪,也许你的意思是Sn=n*a+l/2?。进行这两项更改后,代码应如下所示:

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; 
        for(int num: ar)
        {
            sum = sum+num;
        }

        int n = ar.length;
        int a = ar[0];
        int l =ar[ar.length - 1];
        int total = (n * (a + l)) / 2;
        System.out.print("The missing number is "+(sum - total));
        // outputs 0 which is correct nothing is missing

        // Now if you remove say 12 from the array
        // by changing the array to int ar [] = {1,2,3,4,5,6,7,8,9,10,11,0,13};
        // you should get back -12 which means 12 is missing
    }
}

您可以使用下面的逻辑,使用和理解起来要简单得多

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;
        }
}

如果你不想用我上面的逻辑。您必须更改代码: 编辑以下内容:

int n = ar.length+1;
n被分配为ar.length+1,因为需要+1来补偿数组列表中缺少的元素

此外,公式未正确写入代码:

total = (n* (a + l))/2;
如果先将n除以2,它将截断小数点后的位置,因为n是整数而不是浮点数。因此,当n不是偶数时,逻辑将失败

最后,缺少的数字是总和,而不是相反,因为“总数”包含缺少的数字,“总和”不包含

System.out.print("The missing number is "+(total-sum));

尚未完成解决方案: