执行时不正确的c ++输出

时间:2018-07-07 11:06:05

标签: c++

我正在尝试复制以下程序,但不包括cout函数,这是具有cout函数的程序:

UI

运行时显示

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
  bool incorrect = 1;
  int temp;
  int i = 0;
  int peopleInGroup = 1;
  string x = "";
  int max;
  stringstream ss;
  cout << "Input the number of people in a group: 2 to  ";
  getline (cin, x);
  ss << x;
  ss >> max;
  while(incorrect == 1)
  {
      i++;
      cout << "Testing: " << i << endl;
      peopleInGroup = 1;
      while(peopleInGroup < max)
      {
          peopleInGroup++;
          cout << "Remainder of (" << i << " /" << peopleInGroup << ") =" << (i % peopleInGroup) << "     =" << (peopleInGroup - 1) << "     ";
          if((i % peopleInGroup) == (peopleInGroup - 1))
          {
              cout << "TRUE" << endl;
              if(peopleInGroup == max)
              {
                  incorrect = 0;
          break;
              }
              else{}
          }
          else
          {
              cout << "FALSE" << endl;
              break;
          }
      }
  }
  if(incorrect == 0)
  {
      cout << endl << "The answer is " << i;
  }
  else
  {
      cout << endl << "Unable to find the answer";
  }
  cin >> temp;
}

当我输入3时,它会显示为5,这是正确的:

Input the number of people in a group: 2 to 

没有提示,但是当我这样做时,程序给出了错误的答案:

Input the number of people in a group: 2 to 3
...
The answer is 5

始终是

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
  bool incorrect = 1;
  int temp;
  int i = 0;
  int peopleInGroup = 1;
  string x = "";
  int max;
  stringstream ss;
  cout << "Input the number of people in a group: 2 to  ";
  getline (cin, x);
  ss << x;
  ss >> max;
  while(incorrect == 1)
  {
      i++;
      peopleInGroup = 1;
      while(peopleInGroup < max)
      {
          peopleInGroup++;
          if((i % peopleInGroup) == (peopleInGroup - 1))
          {
          if(peopleInGroup == max)
          {
            incorrect = 0;
          }
          }
      }
  }
  if(incorrect == 0)
  {
      cout << endl << "The answer is " << i;
  }
  else
  {
      cout << endl << "Unable to find the answer";
  }
  cin >> temp;
}

例如,如果我输入3,则结果为2

1 个答案:

答案 0 :(得分:0)

您错过了以下代码中的break语句。

cout不是必需的,但是break语句要从执行块中出来。如果按照上面的代码放置break语句,则将获得所需的输出