给定数组java中邻居对的绝对差值之和

时间:2021-04-07 18:24:14

I need to write a program for some kind of keypad that would look like this if d=15. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

如果d = 15,我需要为某种类型的键盘编写一个程序。 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

User input should be d(length of this keypad), n(how many buttens sbd presses, eg. 3) and the three buttons, chosen by user eg. 4 7 2.

用户输入应为d(此键盘的长度),n(多少次按下sbd,例如3)和用户选择的三个按钮,例如。 4 7 2。

Then, the program is supposed to calculate the length between all these input integers (in this case from 4 to 7 and then from 7 to 3, which is 7) and print the sum.

然后,程序应该计算所有这些输入整数之间的长度(在这种情况下从4到7然后从7到3,即7)并打印总和。

I've somehow managed to come to the point where the only thing i don't know how to do is how to actually sum all the pair differences and print it.

我已经设法达到这样的程度,我唯一不知道该怎么做的是如何实际总结所有的对差异并打印出来。

The code:

int d=sc.nextInt();    
int n=sc.nextInt();

 int arr[]=new int[n];
    for(int i=0;i<n;i++){//for reading array
    arr[i]=sc.nextInt();

    }

        int sum=0;
        int diff=0;

        for(int i=0;i<=arr.length-1;i++) {
            if(i<)
                diff = Math.abs(arr[i+1]-arr[i]);    
        }
        sum+=diff;
        System.out.println(sum);

but basically the only thing this does is return the difference between the last two values of the array.

但基本上唯一能做的就是返回数组最后两个值之间的差异。

How do i fix it?

我如何解决它?

1 个解决方案

#1


1  

The thing you've missed was summing outside of the cycle, you need to do that inside of the cycle as you'd like that to be done for each of the pairs you calculate difference for

你错过的东西是在周期之外求和,你需要在周期内做这个,因为你想要为你计算差异的每个对完成

for(int i=0;i<=arr.length-1;i++) {
    diff = Math.abs(arr[i+1]-arr[i]);   
    sum+=diff; // you need to move this into the cycle
}

#1


1  

The thing you've missed was summing outside of the cycle, you need to do that inside of the cycle as you'd like that to be done for each of the pairs you calculate difference for

你错过的东西是在周期之外求和,你需要在周期内做这个,因为你想要为你计算差异的每个对完成

for(int i=0;i<=arr.length-1;i++) {
    diff = Math.abs(arr[i+1]-arr[i]);   
    sum+=diff; // you need to move this into the cycle
}