This is a C language array problem. Outputs the closest number to the number entered in the array

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

It takes an integer from the array and outputs the element and difference of the most approximate value.

The desired terminal output is as follows.

[ 10 20 30 40 50 60 70 80 90 ]

Enter an integer: 23

The second element, 20, is closest to 23. The difference is 21.

First of all, I coded it like this, but the value is printed out.

I'd really appreciate your help.

#include <stdio.h>
#include <math.h> 
#include <limits.h> 
#define SIZE 9

int main(void)
{
    int user, th, i;
    int diff = 0;
    int near = 0;
    int abs = 0;
    int min = INT_MAX;
    int list[SIZE] = {10, 20, 30, 40, 50, 60, 70, 80, 90};

    printf("[");
    for (i = 0 ; i < SIZE ; i++) {
        printf("%d ", list[i]);
    }
    printf("]\n");


    printf ("Enter an integer:");
    scanf("%d", &user);


    for (i = 0 ; i < SIZE ; i++) {
        diff = user - list[i];
        if (abs < min) {
            min = abs;
            near = list[i];

            printf("%dth element %d" is closest to %d. The difference is %d.\n", th, near, user, diff);
            break;
        }
    }

    return 0;
}

c array

2022-09-20 14:37

1 Answers

int abs(int num)

https://docs.microsoft.com/ko-kr/cpp/c-runtime-library/reference/abs-labs-llabs-abs64?view=msvc-170

#include <stdio.h>
#include <math.h>
#include <limits.h>
#include <stdlib.h>
#define SIZE 9

int main(void)
{
    int user, th, i;
    int diff = 0;
    int near = 0;
    int min = INT_MAX;
    int list[SIZE] = {10, 20, 30, 40, 50, 60, 70, 80, 90};

    printf("[");
    for (i = 0 ; i < SIZE ; i++) {
        printf("%d ", list[i]);
    }
    printf("]\n");


    printf ("Enter an integer:");
    scanf("%d", &user);


    for (i = 0 ; i < SIZE ; i++) {
        diff = user - list[i];
        if (abs(diff) < min) {
            min = abs(diff);
            near = list[i];
            th = i;
        }
    }
    printf("%dth element %d" is closest to %d. The difference is %d.\n", th, near, user, min);
    return 0;
}

[10 20 30 40 50 60 70 80 90 ]
Enter an integer: 24
The first element, 20, is closest to 24. The difference is four.
[10 20 30 40 50 60 70 80 90 ]
Enter an integer: 26
The second element, 30, is closest to 26. The difference is four.


2022-09-20 14:37

If you have any answers or tips


© 2022 pinfo. All rights reserved.