当前位置:网站首页>CSDN daily practice - find the closest element and output the subscript

CSDN daily practice - find the closest element and output the subscript

2022-06-11 00:00:00 Blue stars

Examples are as follows : An array {915,941,960,976,992,1015,1034,1050,1073,1089,1115,1131,1150,1166,1182,1208,1227}; The target value is assumed to be 1000, The closest element is 992, Subscript to be 4

#include <stdio.h>
int main()
{
    int min = (1 << 31) - 1;// initialization int Type of , It becomes 32 Maximum number of bits 2^32-1
    int idx = 0;// Use subscript idx Express , And initialize to 1
    int arr[] = { 915, 941, 960, 976, 992, 1015, 1034, 1050, 1073, 1089, 1115, 1131, 1150, 1166, 1182, 1208, 1227 };
    int n = 1000;
    for (int i = 0; i < sizeof(arr) / sizeof(int); i++)//sizeof(arr) / sizeof(int) Indicates that in the array int Number of type elements 
    {
        int diff = arr[i] - n;// Index in turn , Calculate the element and n The difference between the 
        if (diff < 0)
            diff = -diff;// The difference is less than 0 Go to absolute value 
        if (diff < min)
        {
            min = diff;// Let the number with the smallest absolute value be the new min
            idx = i;// Record subscripts ( from 0 Indexes )
        }
    }
    printf(" The closest thing is %d  The subscript is %d", arr[idx], idx);
    return 0;
}

stay c In language 1<<n Express :

Such as 1<<3 Express the 1 Binary system 0000 0001 Shift three bits to the left :0000 1000

That is to say :

n=1    1*2

n=2  1*2*2

n=3   1*2*2*2

int Type account 4 Bytes ,32 position , The maximum is 2^31-1

原网站

版权声明
本文为[Blue stars]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102234471293.html