当前位置:网站首页>csdn每日一练——找出最接近元素并输出下标
csdn每日一练——找出最接近元素并输出下标
2022-06-10 22:35:00 【蓝色满天星星星】
举例如下:一个数组{915,941,960,976,992,1015,1034,1050,1073,1089,1115,1131,1150,1166,1182,1208,1227};目标值假设是1000,最接近元素为992,下标为4
#include <stdio.h>
int main()
{
int min = (1 << 31) - 1;//初始化int类型的,是它成为32位的最大数2^32-1
int idx = 0;//把下标用idx表示,并初始化为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)表示该数组中int类型元素的个数
{
int diff = arr[i] - n;//依次索引,计算出元素与n的差值
if (diff < 0)
diff = -diff;//作差小于0就去绝对值
if (diff < min)
{
min = diff;//让绝对值最小的数作为新的min
idx = i;//记录下标(从0索引)
}
}
printf("最接近的是%d 下标是%d", arr[idx], idx);
return 0;
}在c语言中的1<<n表示:
如1<<3表示把1的二进制0000 0001左移三位即:0000 1000
也即:
n=1 1*2
n=2 1*2*2
n=3 1*2*2*2
int类型占4个字节,32位,最大值是2^31-1
边栏推荐
- LabVIEW obtains the information of all points found by the clamp function
- 可扩展到Max–MCU和MPU开发,使用相同的许可证
- Dell R730 raid5 安装Server 2016(解决磁盘大于2T)
- 1.打开R程序,使用 apply 函数计算1到12按先后次序每隔3个数一组的和。即,计算1+4+7+10=?2+5+8+11=?,3+6+9+12=?
- Im instant messaging source code with tutorial /uniapp instant messaging source code, with installation tutorial
- 【数学】【连续介质力学】流体力学中的对称张量、应变张量和应力张量
- PHP实现iframe跨站替换文字/替换iframe网站文字的方法
- 怎么生成自动参考文献(简单 有图)
- LabVIEW错误“内存已满 - 应用程序停止在节点”
- Analysis of Genesis public chain
猜你喜欢

It is known that the transverse grain pressure resistance of a certain wood obeys n (x, D2). Now ten specimens are tested for transverse grain pressure resistance, and the data are as follows: (unit:

LabVIEW error "memory full - Application stopped on node"

LabVIEW和VDM提取色彩和生成灰度图像

LabVIEW 禁止其他可多核心处理的应用程序在所有核心上执行

What Fiddler does for testing

Unity 脚本无法显示C#源码的中文注释 或者VS创建的脚本没有C#源码的注释

How to generate automatic references (simple drawings)

IGBT与三代半导体SiC双脉冲测试方案

300 questions on behalf of the first lecture on determinant

考研英语词汇 unit1
随机推荐
Redis list list common commands
LabVIEW中创建毫秒时间标识
Interview questions - written examination
The data file insurance CSV contains 1338 observations, that is, the registered beneficiaries of the insurance plan and the characteristics that represent the characteristics of patients and the total
R 语言绘制二维正态分布的密度曲面图;
PHP implementation of iframe cross site text replacement / iframe website text replacement
【无标题】
The shell script of pagoda plan task regularly deletes all files under a directory [record]
Is it safe to open an account online in Shanghai?
Is qiniu's securities account true? Is it safe?
Is it safe to open an account in Shanghai Securities?
Creating dynamic two-dimensional array with C language
长投学堂开户安全吗?靠谱吗?
Fiddler creates an autoresponder
Dell R730 raid5 安装Server 2016(解决磁盘大于2T)
第六章——分枝限界法
An adaptive size / full screen display method for iframe frames
LabVIEW pictures look bright or dark after being cast from 16 bits to 8 bits
LabVIEW get IMAQ get last event coordinates
宝塔计划任务Shell脚本定时删除某各目录下所有文件【记录】