2016-04-10 68 views
1

我一直在试着用10个问题做一个随机数字测验,但是我的循环并没有停止,只是第一个问题。如何用C++中的10个问题进行随机数字测验?

我试图让循环一次一个问题,并且当用户回答question1时,它将进入question2等等,直到所有10个问题都被回答,并且每个正确的答案将被添加到分数1每个问题的点数。谁能帮我这个?

编辑:1 好的我改变了代码,就像你说的这样吧?

#include <cstdlib> 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int Player = 0; 
    int question = 1; 
    int nquestion = 10; 
    int choice = 0; 

    int qanswere1 = 0; 
    int panswere1 = 0; 

    int num1 = 0; 
    int num2 = 0; 
    int score = 0; 

    cout << "Lets Start" <<endl; 
    cout << "[1] Addition" <<endl; 
    cout << "[3] End" <<endl; 
    cout << "Choose: "; 
    cin >>choice; 

    if(choice == 1){ 
     choice = 0; 

     cout << "Level" <<endl; 
     cout << "[1] Easy (1 - 10)" <<endl; 
     cout << "Choose: "; 
     cin >> choice; 

     while(choice == 1){ 
      for(question = 1; question <= nquestion; question = question + 1){ 
       num1 = rand()%10 +1; 
       num2 = rand()%10 +1; 
       cout<<num1<<"+"<<num2<<endl; 
       qanswere1 = num1 + num2; 
       cin>>panswere1; 
      }} 
     if(panswere1 == qanswere1){ 
      score = score + 1; 
     } 
     else{ 
     } 
     return 0; 
    } 
} 
即使有这样的代码,它仍然超出了10个问题,我是做错了什么

..

回答

0

为了使循环停靠,输入一个问题,然后再进行进一步的问题(S ),尽量采取对输入的循环内的变量panswere1,就像这样:

for(question = 1; question <= nquestion; question = question + 1){ 
    num1 = rand()%20 +1; 
    num2 = rand()%20 +1; 
    coutnum1"+"num2endl; 
    qanswere1 = num1 + num2; 
    cin>>panswere1; 
} 

注1:看什么的第一个for循环是干什么的,它可以很好地通过

实现
while(choice == 1){.. 

不影响代码的可读性。

干杯!

编辑1:
为了使代码停在10个问题,你将有一个简单的,如果条件来代替外环

for (choice ==1; choice==1; choice==1){.. 

if(choice == 1){.. 

问题与for循环是它将运行无限次,因为你没有添加任何机制来限制它将执行的次数。如果你不得不将问题的数量限制在10个,我建议用这个if语句替换循环。

编辑2:
你将不得不使用if条件来代替内,而环太:
更换

while(choice == 1){.. 

if(choice == 1){.. 
+0

THX的作品!但我怎么能限制到10现在超过10现在对不起,如果我没有理解它 –

+0

@genesia假设你已经将10分配给你的变量'nquestion',循环将运行10次。 –

+0

不要忘记接受答案,如果它可以解决你的疑问:) –