【问题标题】:C++ integer odd/even counter issue [duplicate]C ++整数奇数/偶数计数器问题[重复]
【发布时间】:2018-02-03 03:22:57
【问题描述】:

所以我正在编写一个从 .dat 文件中收集整数列表的文件,并且 计算有多少奇数和偶数。

我为此编写的代码大部分都有效。但是有一个模糊的场景会失败。如果 .dat 文件中的一行以偶数结尾,它将比它应该的多计数 1 个偶数和少 1 个奇数。

关于发生了什么的任何想法? 我尝试了什么:

cout << "What is the name of the input file? ";
cin >> fileName;

infile.open(fileName);
if (infile.fail())
{
    cout << "Error opening " << fileName << endl;
}
else 
{
    infile >> number;
    while (!infile.eof())
    {
        count1++;
        infile >> number;

        if (number % 2 != 0)
        {
            odd++;
        }
        else
        {
            even++;
        }
    }
}

infile.close();


cout << "The number of integers is: " << count1 << endl;
cout << "There are " << odd << " odd integers and " << even << " even integers" << endl;

system("pause");
return 0;
}

【问题讨论】:

  • 你跳过第一个数字,(在循环之前)。
  • 示例输入在哪里?

标签: c++ integer counter


【解决方案1】:

问题在于使用

while (!infile.eof())

决定何时终止循环。见Why is iostream::eof inside a loop condition considered wrong?

使用以下内容:

else
{
   while ( infile >> number )
   {
      count1++;

      if (number % 2 != 0)
      {
         odd++;
      }
      else
      {
         even++;
      }
   }
}

【讨论】:

  • 非常感谢修复它。
  • @Josh,很高兴听到这个消息。我希望您阅读我链接到的帖子以完全理解我建议的解决方案。
  • 当您发现某个问题表现出已经被询问过的问题时,请标记重复项,不要写另一个不太完整的答案。
  • @BenVoigt。我原则上同意。我认为专门解决如何重新排列 OP 代码的答案会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
相关资源
最近更新 更多