gpt4 book ai didi

c++ - 数组中最接近的值

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:11 25 4
gpt4 key购买 nike

我应该编写一个传递两个参数的函数:一个 int 值的一维数组和一个整数值。该函数在数组中查找值最接近第二个参数的值。我的代码有效,但当我输入数字 1-5 时,我的输出为 0。当我输入大于 5 的数字时,我开始获得准确的结果。我不太清楚为什么会这样,但到目前为止,这是我的代码:

#include <iostream>
#include <cmath>
using namespace std;

const int MAX = 5;

int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;

for(int x = 0;x < MAX; x++)
{
if(value > abs(key - anArray[x]))
{
value = abs(key - anArray[x]);
num = anArray[x];
}
}

return num;

}

int main()
{
int A[MAX] = {3,7,12,8,10};

int search;

int nearest;

cout << "Enter a number to search: ";

cin >> search;

nearest = searchNearest(A,search);

cout << "The nearest number is: " << nearest << endl;

system("pause");
return 0;

}

最佳答案

在您的原始代码中,数字 1-5 最接近数组的第一个元素。正因为如此,if语句中的代码永远不会被执行,当你返回num时,你返回它的初始值,恰好是0。要解决此问题,只需以不同方式初始化 num:

int num = anArray[0];  // <-- used to be 0

关于c++ - 数组中最接近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com