[英]Finding the smallest number in a set of Data
我有以下形式的一組數據:
a1 b1 c1 d1
a2 b2 c2 d2
...
an bn cn dn
我的目標是找到c列中值最小的行。
我做了以下事情:
const int limit=100000;
float Array[limit][4];
int main() {
double a, b, c, d, smallest, ref1, ref2;
ifstream in("data.dat");
int idx=-1, point;
while(!in.eof()) {
idx++;
in >> a >> b >> c >> d;
Array[idx][0]=a; Array[idx][1]=b; Array[idx][2]=c; Array[idx][3]=d;
} \\end of while
in.close();
int count=idx;
for(int i=1; i<count; i++) {
ref1= Array[0][2];
ref2 = Array[i][2];
if(ref2 < ref1) {ref1 = ref2; point=i;} //I thought this will save the smallest value
smallest = ref1; point= i;
} \\end for
cout << "point" << Array[point][0] << Array[point][1] << .. etc.
return 0;
}
但是,輸出是數據中的最后一點。 (在輸入此問題時,我意識到在讀取新行時ref1將始終是Array [0] [2]。所以現在我完全迷失了!)
如何將一個點保存為參考點,以便與其他數據進行比較,並且每次與較小的點進行比較時將其更改為較小的值?
更新 :我通過使用ref1 = Array [0] [2]來解決此問題; 退出for循環。
為了證明您在一組值中找到了最小值,請將for循環更改為以下內容:
int smallest_val = std::numeric_limits<int>::max();
for(int i=0; i < idx; i++)
{
if (Array[i][2] < smallest_val)
smallest_val = Array[i][2];
}
基本上,你通過設置開始smallest_val
以最大的可能值,它可以有可能使用std::numeric_limits<int>::max()
現在,數組中的每個值都必須至少等於smallest_value
或更小(什么都不能更大)。 當您遍歷數組時,一旦擊中的值小於當前在smaller_value
的值,則可以正確地將在smaller_value
的值重新分配給該新的較低值。 通過以int
類型表示的最大可能值開始,可以避免遇到最小值彼此相對的問題。 使用數學歸納法,對於您在此處嘗試執行的操作,這種方法是不必要的。
您應該像在循環外一樣設置一個引用,並更新最小的btw,不要將浮點數和雙精度數混合使用,但這是示例代碼:
#include <iostream>
#include <fstream>
using namespace std;
const int limit=100000;
float Array[limit][4];
int main() {
double a, b, c, d, smallest, ref1, ref2;
ifstream in("data.dat");
int idx=-1, point;
while(!in.eof()) {
idx++;
in >> a >> b >> c >> d;
Array[idx][0]=a;
Array[idx][1]=b;
Array[idx][2]=c;
Array[idx][3]=d;
} //end of while
in.close();
int i = 0;
int count;
smallest = Array[i][2];
for( i=1; i<count; i++) {
ref2 = Array[i][2];
if(ref2 < smallest) {
smallest = ref2;
point=i;
}
}
std::cout << "point" << Array[point][0] << " "
<< Array[point][1] << " "
<< Array[point][2] << " "
<< Array[point][3] << std::endl;
return 0;
}
帶數據文件
1 2 3 4
2 3 8 9
1 3 5 2
1 1 1 1
2 4 2 4
3 1 0 1
HTH
另外,輸入回路控制不正確:
while(!in.eof()) {
讀取失敗之前,不會觸發eof()。 實際上,這意味着輸入循環將額外執行一個時間,並且最后一次您將獲得無用的值。
正確的測試是
while(in >> a >> b >> c >> d) {
如果任何提取程序失敗(希望是因為in
位於輸入的末尾,則while循環將結束。
這里的問題是,您永遠無法與最小的產品進行比較。 您在ref1和ref2之間分配最小值,而不考慮先前的迭代。 另外,ref1始終是數據中的第一個值,因此,如果最后一個值大於第一個值,則最小的將永遠是最后一個。 將循環更改為Jason發布的內容將解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.