我不知道为什么我的程序没有进入循环

时间:2015-09-26 14:47:16

标签: c++ loops

#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&lt; 10){if(population == 1)循环。我使用cout检查了它,人口正在减少到一位数

1 个答案:

答案 0 :(得分:1)

是的,return是原因。

另外,让我帮您解决代码问题。

1.-检查population是否小于10是否真的有意义?如果你想避免不合逻辑的错误,可以更好地与负值进行比较,并警告用户是否在文本文件中指明了这一点。使用while (population >= 10),您将强制该值变为&lt;比10。

2.-为什么要进行所有复杂的比较?怎么样:

int counter[10];
counter[population-1]++;

while (population >= 10) {
  population = (population/10);
} 

而不是使用所有这些ifs并一次又一次地比较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