我想创建一个最适合的内存分配解决方案。
int main()
{
int input;
int memoryBlock[ARRAY_SIZE] = {5, 10, 3, 9, 7};
int bestFit;
cout << "Please enter the memory size you want to allocate: ";
cin >> input;
for (int i = 0; i < ARRAY_SIZE; i++){
if (memoryBlock[i] - input < 0 ){
}
else {
bestFit = memoryBlock[i];
}
}
cout << bestFit;
}
根据上面的代码,如何修改它,else {}
将选择最接近的数字?
提前致谢。
答案 0 :(得分:2)
更改您的代码,使其仅在更好的时候替换bestFit:
int bestFit = -1;
for (int i = 0; i < ARRAY_SIZE; ++i) {
if (memoryBlock[i] - input >= 0 && memoryBlock[i] < bestFit) {
bestFit = memoryBlock[i];
}
}