我正在嘗試使用 for 回圈從檔案中讀取 100,000 個 int 值。我也想把它們加起來,找到一個最小值,然后找到一個最大值。我的代碼現在只有在我將讀取值的數量從 100,000 更改為 100 時才能正確讀取。即使是 200 個值,我的代碼也只是跳過資料并且沒有給出正確的輸出。在讀取大量值時,誰能看到我的代碼可能出錯的地方?謝謝你!
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int number;
int sum;
int big, small = 0;
string file;
cout << "Enter a file name: ";
cin >> file;
ifstream inFile(file);
for (long i = 0; i < 100000; i )
{
if (!(inFile >> number))
{
cout << "ERROR!";
return 1;
}
}
for (long i = 0; i < 100000; i )
{
inFile >> number;
sum = sum number;
if (number < small)
{
small = number;
}
if (number > big)
{
big = number;
}
}
cout << sum << endl;
cout << big << endl;
cout << small << endl;
return 0;
}
另外,我的輸入檔案是這樣排列的
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
...
...
...
當然還有其他數字
uj5u.com熱心網友回復:
正如其他人所說,您的第一個回圈正在讀取和丟棄整數,然后您的第二個回圈從第一個回圈停止的地方開始,而不是再次從檔案的開頭開始。您應該只使用 1 個回圈。
在進入增加它們的回圈之前,您也沒有初始化您的sum和big變數。
嘗試更像這樣的事情:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int number, sum, big, small;
string file;
cout << "Enter a file name: ";
cin >> file;
ifstream inFile(file);
if (!(inFile >> number))
{
cout << "ERROR!";
return 1;
}
sum = small = big = number;
for (int i = 1; i < 100000; i)
{
if (!(inFile >> number))
{
cout << "ERROR!";
return 1;
}
sum = number;
if (number < small)
{
small = number;
}
if (number > big)
{
big = number;
}
}
cout << sum << endl;
cout << big << endl;
cout << small << endl;
return 0;
}
uj5u.com熱心網友回復:
編輯筆記
正如@RemyLebeau 指出的那樣,我犯了沒有初始化bigor的錯誤sum,我因為a, b, c = 0沒有初始化 a 或 b 而只初始化 c的經典錯誤而傻了。
其次,正如 Remy 所指出的,我沒有意識到流具有operator!, 用于檢查流上是否發生故障。
考慮到這一點,這是我的更新版本,以下是供后代使用的原始版本:
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int number;
int sum = 0, big = 0, small = 0;
string file;
cout << "Enter a file name: ";
cin >> file;
ifstream inFile(file);
for (long i = 0; i < 100000; i )
{
if (!(inFile >> number))
{
cout < "ERROR!";
return 1;
}
sum = sum number;
if (number < small)
{
small = number;
}
if (number > big)
{
big = number;
}
}
cout << sum << endl;
cout << big << endl;
cout << small << endl;
return 0;
}
原帖
首先,sum應該初始化為零,因為它的值總是由對其自身的加法結果決定。
int sum = 0;
其次,在您的第一個回圈中,您正在從檔案中讀取一個變數,然后丟棄該變數的值。此回圈具有推進檔案指標的副作用,因此如果您在第一個回圈中讀取 100000 個值,則第二個回圈從檔案中的第 100001 個值開始。
我真的看不出有任何理由在兩個單獨的回圈中執行此操作,而且我也不明白您為什么要檢查 的“結果” inFile >> number,因為無論如何它的回傳值永遠不會為空:
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int number;
int sum, big, small = 0;
string file;
cout << "Enter a file name: ";
cin >> file;
ifstream inFile(file);
for (long i = 0; i < 100000; i )
{
inFile >> number;
sum = sum number;
if (number < small)
{
small = number;
}
if (number > big)
{
big = number;
}
}
cout << sum << endl;
cout << big << endl;
cout << small << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/324526.html
上一篇:在打字稿中的foreach回圈內承諾,從回應構造陣列并等待所有完成
下一篇:如何遍歷多列以生成多個交叉表
