#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int ranking = 0;
int population = 0;
float leadingNumPercent = 0;
float oneCounter = 0;
float twoCounter = 0;
float threeCounter = 0;
float fourCounter = 0;
float fiveCounter = 0;
float sixCounter = 0;
float sevenCounter =0;
float eightCounter =0;
float nineCounter =0;
float overAllCounter =0;
int i =0;
string countryName;
ifstream inFile;
inFile.open("test.txt");
while(!inFile.eof()){
inFile >> ranking;
inFile >> population;
getline(inFile, countryName);
while (population >= 10) {
population = (population/10);
}
if (population < 10){
if (population == 1){
oneCounter++;
return oneCounter;
}
if (population == 2){
twoCounter++;
return twoCounter;
}
if (population==3){
threeCounter ++;
return threeCounter;
}
if (population==4){
fourCounter ++;
return fourCounter;
}
if (population==5){
fiveCounter ++;
return fiveCounter;
}
if (population==6){
sixCounter ++;
return sixCounter;
}
if (population==7){
sevenCounter ++;
return sevenCounter;
}
if (population==8){
eightCounter ++;
return eightCounter;
}
if (population==9){
nineCounter ++;
return nineCounter;
}
}
leadingNumPercent = (oneCounter / 238)*100;
cout << leadingNumPercent;
}
inFile.close();
return 0;
}
これが私がhttp://www.buildingthepride.com/faculty/jajerkins/cs155-01/population2014.txtにリンクしているtest.txtファイルです。プログラムはif(population <10){if(population == 1)ループに入らないようです。coutを使って確認したところ、人口は1桁に減っています。
はい、それreturn
が理由です。
また、私はあなたのコードであなたを助けさせてください。
1.-がpopulation
10より小さいかどうかを確認することは本当に意味がありますか?非論理的なエラーを回避したい場合は、負の値と比較して、テキストファイルでそのことを示した場合はユーザーに警告してください。ではwhile (population >= 10)
、あなたは値を強制されている10以上<なります。
2.-なぜそのような複雑な比較をすべて行うのですか?どうですか:
int counter[10];
counter[population-1]++;
後
while (population >= 10) {
population = (population/10);
}
これらすべてのifを使用population
して、何度も比較する代わりに。
3.-なぜreturn
とにかく使っているのですか?あなたはプログラム全体を壊しています。またinFile.close()
、そのようにはなりません。どうですか:
for(int i=0 ; i<10 ; i++)
{
cout << "Number " << i << ": " << counter[i] << std::endl;
}
行の後
inFile.close();
4.-いくつかの値をテストしたい場合はbreak
、while(!inFile.eof())
ループしcout
て変数を表示しましょう。
5.-float
本当に整数を意味する場合は使用しないでください。数量を数えているので、int
それ以上を使用してくださいunsigned int
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加