0

我正在尝试这样做,因此如果用户输入的数字小于 4 或大于 10,则会提示他们无效并输入新数字。我遇到的问题是,如果他们确实输入了正确的数字,它就不会继续到下一部分。这是我到目前为止所拥有的:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>

int NewRandomNumber (int n);
void MakeQuestion (int n, int& a, int& b, int& atimesb);
bool UserAnswer (int a, int b, int atimesb);
void PrintScore (int numCorrect, int numAsked);

using namespace std;

int main()

{
string name;
int n;
string s;




cout << "Welcome to Multiplication Quiz 1000!" << endl;
cout << "Firstly what is your name?\n" << endl;

cin >> name;

cout << "\nHi " << name <<" !" << endl;
cout << "What difficulty would you like your quiz to be? Enter a value from [4 to 12]

      \nwith 4 being the easiest:\n" << endl;

do
{
cin >> s;
n = atoi(s.c_str());

if ( n >= 4 || n <= 10)



  if ( n < 4 || n > 10)
    {cout << "invalid. try again" << endl;
    }



{cout << "Ok" << endl;
cout << NewRandomNumber (4);
}

}
while ( n >= 4 || n <= 10);


 return 0;

 }

int NewRandomNumber (int n)

{ 

    n = rand()% 10 + 1;




return (n);

 }

void MakeQuestion (int n, int& a, int& b, int& atimesb)

{
}
4

3 回答 3

4

你的while( n >= 4 || n <= 10)条件永远是真实的。你应该去 while (n <= 4 || n >= 10)

有几种方法可以解决您的问题,就像它已经发布在这里一样。我会用一个continue声明,就像 slacker 说的那样,但一定要改变你的while条件,否则它不会起作用。它会是这样的:

while (true) {
    cin >> s;
    n = atoi(s.c_str());

    if (n <= 4 || n >= 10) {  
    // handles your exception and goes back to the beggining of the loop
    continue;
    }
    else {
    // the number was correct, so make your magic happen and then...
    break;
    }
} 
于 2013-03-19T04:06:47.760 回答
1

我想你错过了继续声明。

// .............

        if ( n < 4 || n > 10)
            {cout << "invalid. try again" << endl;
             continue;
            }

    //..............
于 2013-03-19T03:50:25.783 回答
1

使用标志以这种方式尝试:

int flag=0;

do{

cin >> s;
n = atoi(s.c_str());


if ( n < 4 || n > 10)
{
  cout << "invalid. try again";
}
else
{
   flag=1;
   cout<<"OK"
}
}while(flag=0);

自从我用 C++ 编程以来已经有一段时间了,所以语法上可能存在一些小问题。但是这里的逻辑应该没问题。

于 2013-03-19T03:51:30.220 回答