[英]Find the number closest to another number c++
我有一個文件,里面有一個整數列表,試圖找到最接近200的整數。我整天都在進行此操作,並且在來到這里之前,我自己做了很多嘗試。 我知道我必須采取不同的做法並進行比較,但這是到目前為止我所獲得的。 我們還沒有介紹數組或創建函數。
文件中的編號列表55 67 458 23 81 33 782 375 528 405 324 950 46 14 864 551 38 167 518 630
我到目前為止的代碼是
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
ifstream datain;
datain.open("c:\\DataFile2.txt");
int count, sum, num, min, max;
count = sum = num = min = max = 0;
while(datain)
{
datain >> num;
sum = abs(num - 200);
if(sum < min)
sum = num;
}
變量名沒有太大意義,因為我從程序的其他部分重用了它們。 我嘗試了這種不同的變體,並且嘗試了其他方法。 輸出始終是開始時設置的數字。 我仍然無法解決這個問題,希望能得到我的幫助。
問題是您要用0初始化min
,因此條件sum < min
永遠不會為真。
一個簡單的解決方案是在進入循環之前,使用從datain
獲得的第一個值初始化min
。
盡管正如克里斯所說,還有更優雅的解決方案,例如使用std::min_element
。
如果您有一個可排序且小於(<)的向量,則可能是一種解決方案:
#include <algorithm>
#include <vector>
using namespace std;
/*
* Find the element in haystack closest to needle.
* NOTE: haystack must be sorted
*/
template<typename T>
T find_closest (T needle, std::vector<T> haystack) {
/* handle special cases where needle
* is smaller than the first or bigger
* than the last element
*/
if (needle <= haystack.front()) {
return haystack.front();
}
if (needle >= haystack.back()) {
return haystack.back();
}
auto closest = adjacent_find(haystack.begin(), haystack.end(),
[&needle] (T i, T j) {return i =< needle && needle <= j;});
return (needle-(*closest) < *(closest+1)-needle) ? *closest : *(closest+1);
}
int main ()
{
int needle = 200;
std::vector<int> haystack = {55, 67, 458, 23, 81, 33, 782, 375, 528, 405, 324,
950, 46, 14, 864, 551, 38, 167, 518, 630};
sort(haystack.begin(), haystack.end());
int found = find_closest(needle, haystack);
}
有幾件事:
num = 0是錯誤的,不保存最佳數字是錯誤的
最小= MAXINT;
int besthit;
while(datain)
{
datain >> num;
sum = abs(num - 200);
if(sum < min) {
besthit = num;
min = sum;
}
}
應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.