我試圖從一個文本檔案中讀取一個數字,指的是每年的人口,并且每年每千名居民都有一個星號。當我運行程式時,星號會無限運行,我不知道如何每 1000 名居民只運行一個。
#include <iomanip>
#include <fstream>
#include <iostream>
#include <string>
using std::endl;
using std::ifstream;
//start of program
int main ()
{
ifstream inFile;
int year, population, num, i;
//includes the popluation.txt file
inFile.open("population.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while(inFile)
{
// inFile >> year >> population;
cout << year << endl;; //process data
inFile >> year >> population; // next line
}
while(population >= 1000)
{
for (population = 0; population < num; i)
cout << "*" << endl;
population ;
}
inFile.close();
return 0;
}
人口.txt
1900 2230
1920 4532
1940 5783
1960 6466
1980 8222
2000 10348
uj5u.com熱心網友回復:
在這種情況下,記住計算機編程的黃金法則非常重要:“您的計算機總是完全按照您的要求執行,而不是您希望它執行的操作”。
因此,讓我們探索一下您告訴計算機執行的操作:
while(inFile)
{
只要inFile處于有效狀態,您就告訴您的計算機執行 while 回圈中的陳述句。好的,那么你告訴你的計算機做什么,只要inFile它處于有效狀態?
cout << year << endl;; //process data
inFile >> year >> population; // next line
您告訴您的計算機列印 中的內容year,然后從和inFile中讀取。yearpopulation
因此,只要inFile處于有效狀態,您就會從檔案中讀取year和population. 并且絕對不做任何其他事情。
那是你想讓你的電腦做的嗎?根據你的描述,當然不是。您希望您的計算機為每個year和population. 但是您告訴您的計算機做其他事情:讀取整個檔案,每次讀取year和population. 所以這就是你的計算機要做的事情,在這部分完成之前它不會做任何其他事情。
year此外,您可能已經注意到,您甚至在讀取任何內容之前就告訴您的計算機顯示其中的內容。畢竟,您告訴您的計算機:year在繼續閱讀之前先顯示其中的內容inFile。所以,在你讀到任何東西之前,year你告訴你的電腦顯示year. 當然,這沒有多大意義,但這就是您告訴計算機要做的事情。
但是,在告訴您的計算機完成所有這些之后,在到達檔案末尾之后,您又告訴您的計算機做什么?
while(population >= 1000)
好的,您告訴您的計算機執行以下所有操作,只要population是 1000 或更多。
for (population = 0; population < num; i)
cout << "*" << endl;
population從0開始,i只要population小于num?
是什么num?顯示的代碼中沒有任何內容可以設定num為任何內容。那么,你的電腦在這里應該做什么呢?是什么i?您也沒有事先告訴您的計算機是什么i。因此,您的計算機實際上根本不知道您的計算機應該做什么。在 C 中,這就是所謂的“未定義行為”。此時,您的計算機只是舉起手來,做它想做的任何事情,比如列印無數個星號。
我不知道如何每 1000 名居民只經營一家。
這很簡單:只需告訴您的計算機它應該做什么。首先用簡單的英語在一張紙上寫下您希望計算機執行的操作。例如:
次年嘗試讀取,并從檔案中人口。如果這失敗了,你就完成了,就是這樣。
顯示讀取的年份,并將計數器初始化為 0。
計數器是否小于人口規模?如果是這樣,列印一個星號,將 1000 添加到計數器,然后重復。
列印換行符,即行尾。
所以,在寫完所有這些之后,只需將上面的內容直接翻譯成C !而已!你準確地告訴了你想讓你的電腦做什么!
uj5u.com熱心網友回復:
也許您可以使用std::string填充建構式適當地重復 astrixes:
#include <iostream>
#include <fstream>
int main() {
std::ifstream in_file;
in_file.open("population.txt");
if (!in_file) {
std::cout << "Unable to open file";
exit(1);
}
int year, population;
while (in_file >> year >> population) {
std::cout << year << ": " << std::string(population / 1000, '*') << " (" << population << ")" << '\n';
}
in_file.close();
return 0;
}
輸出:
1900: ** (2230)
1920: **** (4532)
1940: ***** (5783)
1960: ****** (6466)
1980: ******** (8222)
2000: ********** (10348)
uj5u.com熱心網友回復:
您可以通過簡單的回圈使用蠻力:for
int quantity = population / 1000;
for (int i = 0; i < quantity; i)
{
std::cout << "*";
}
std::cout << "\n";
上面的代碼使用數學來確定星號的數量。回圈根據數量列印星號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451619.html
標籤:C
上一篇:創建新執行緒c 時代碼崩潰
