我正在尝试获取数组 size
中最近上限(除非找到等效值)的索引使用变量 sum
中的值作为上限,然后在数组中找到相同索引处的值 value
.
例如:如果 sum
中的值是 270,我的程序应该找到位于 size
中索引 6 处的值 280并输出对应value[6]
处的值.
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
double x = 0;
double y = 0;
double sum = 0;
double size[27] = {24, 28, 32, 38, 48, 240, 280, 320, 360, 380,
420, 480, 560, 600, 640, 700, 720, 800, 840,
960, 980, 1120, 1200, 1280, 1440, 1680, 1920};
double value[27] = {.0022, .0026, .0029, .0035, .0044, .0219,
.0256, .0292, .0328, .0384, .0438, .0513,
.0547, .0584, .0641,.0656, .073, .0766,
.0875, .0877, .0897, .1023, .1094, .1169,
.1313, .1531, .175};
cout << "Enter width: " << endl;
cin >> x;
cout << "Enter height: " << endl;
cin >> y;
x = ceil(x) + 3;
y = ceil(y) + 3;
sum = x * y;
}
最佳答案
将您的代码更改为此 -
double x = 0;
double y = 0;
double sum = 0;
int size[27] = {24, 28, 32, 38, 48, 240, 280, 320, 360, 380,
420, 480, 560, 600, 640, 700, 720, 800, 840, 960, 980, 1120, 1200, 1280, 1440, 1680, 1920};
double value[27] = {.0022, .0026, .0029, .0035, .0044, .0219,
.0256, .0292, .0328, .0384, .0438, .0513, .0547, .0584, .0641,.0656, .073, .0766, .0875, .0877, .0897, .1023, .1094, .1169, .1313, .1531, .175};
cout << "Enter width: " << endl;
cin >> x;
cout << "Enter height: " << endl;
cin >> y;
x = ceil(x) + 3;
y = ceil(y) + 3;
sum = x * y;
for (int i=0;i<27;i++)
{
if (size[i]>=sum)
{
cout<<value[i]<<endl;
break;
}
else if(i==26)
{
cout<<"No upper Bound find\n";
}
}
还有其他方法可以解决这个问题。但是正如您所说,您是初学者。我已经给出了简单的暴力破解解决方案。 :)
关于c++ - 搜索数组的上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905678/