C ++ getInt函数

时间:2019-02-27 22:29:11

标签: c++

我有此编程任务,我必须使用c ++中的一个方法,该方法接受2个值,然后继续运行直到用户输入该范围内的值为止,整个问题如下所示:

Q.编写一个名为getInt的函数,该函数接受两个整数(一个低值和一个高值),然后强制 用户输入一个介于低和高之间的值并返回该值。具有较高的默认值 INT_MAX。

我现在已经走了这么远: `

int getInt(int low, int num) {
  int high = INT_MAX;
  while (num > low && num < high) {
    cout << "Invalid: ";
    cin >> num;
  }
  return num;
}

1 个答案:

答案 0 :(得分:0)

您需要对功能进行一些调整。

// high is the second input, not num
// The default value of high is set to INT_MAX
int getInt(int low, int high = INT_MAX)
{
   // The number that you want to receive as input from the user.
   int num = 0;

   // Don't check whether the number is valid without user input.

   cout << "Enter a number: ";
   while ( cin >>  num )
   {
      if ( low <= num && num <= high)
      {
         // Valid number. Return.
         return num;
      }

      cout << "Invalid Input. Enter a number again: ";
   }

   // If you are here, there was an error.
   // Can't return anything valid.
   throw std::string("bad input");

   // Keep some compilers happy even though this line won't be executed.
   return 0;
}