简体   繁体   中英

The sum of differences of array elements from each other

That is my code. But the output is wrong. My expected output is:

input: 1 2 3
output: 3 2 3 ;
but the actual output is 2 1 0 on my code.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n; // create a variables to decide how many number that they want to store on array
    int position[10];
    int sumdiffs[10];
    printf("How many number you want to enter here: ?\n"); // let users enter how much number
    scanf("%d", &n);
    // accept users number
    for (int m = 0; m < n; m++) {
        printf("Please enter number %d:", m + 1);
        scanf("%d", &position[m]);
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            sumdiffs[i] = abs(position[i] - position[j]);
        } 

        printf("%d\n", sumdiffs[i]);
    }

    return 0;
}

That is my test.

How many number you want to enter here: ?
3
Please enter number 1:1
Please enter number 2:2
Please enter number 3:3
2
1
0

You are not computing the sum of differences, you only store each difference so the array sumdiffs contains the last difference.

Note also that your code has undefined behavior for n greater than 10 because you access the arrays beyond their boundaries.

Here is a modified version:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n;
    printf("How many numbers you want to enter here?\n");
    if (scanf("%d", &n) != 1 || n <= 0)
        return 1;
    // arrays defined with the correct size (hopefully not too large)
    int position[n];
    int sumdiffs[n];
    // read the numbers from the user
    for (int m = 0; m < n; m++) {
        printf("Please enter number %d: ", m + 1);
        if (scanf("%d", &position[m]) != 1)
            return 1;
    }

    for (int i = 0; i < n; i++) {
        sumdiffs[i] = 0;
        for (int j = 0; j < n; j++) {
            sumdiffs[i] += abs(position[i] - position[j]);
        } 
        printf("%d\n", sumdiffs[i]);
    }
    return 0;
}

First, clear the accumulated sums:

for (int i = 0; i < n; i++) {
    sumdiffs[i] = 0;

Then, just change

sumdiffs[i] = abs(position[i] - position[j]);

into

sumdiffs[i] += abs(position[i] - position[j]);

to accumulate the differences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM