【发布时间】:2022-01-02 15:03:11
【问题描述】:
我正在用 C++ 编程语言做一个测验程序。我使用了一个 for 循环来遍历每个 switch case,但是当我运行程序时,它只是不断循环 case 0 并且在我回答完我的测验后无法停止循环。我该如何解决?
#include <iostream>
#include <string>
using namespace std ;
void quiz_count () ;
void display_question () ;
void question (string question , string a , string b , string c , string d , char correct_answer) ;
void result () ;
int question_num = 0 ;
int correct = 0 ;
int wrong = 0 ;
int main ()
{
display_question() ;
return 0 ;
}
void quiz_count ()
{
system("cls") ;
cout << "Question Number: " << question_num << "\t\t Correct Answer:" << correct << "\t\t Wrong Answer:" << wrong << endl << endl ;
display_question () ;
}
void display_question()
{
for (int i=0; i<10 ; i++)
{
switch (i)
{
case 0 :
question ( "1) What is recycling?" , "Buying new clothes" , "Collecting and using materials to make something new" , "Throwing things in garbage can" , "Selling items" , 'b' ) ;
break ;
case 1 :
question ( "2) What are the 3R's of the recycling?" , "Redirect, Rude, Round" , "Respectful, Responsible, Right" , "Reduce, Reuse, Recycle" , "Rewrite, Rewind, Respond" , 'c') ;
break ;
case 2 :
question ( "3) What goes into the green bin?" , "plastic" , "glass" , "cans" , "paper" , 'b' ) ;
break ;
}
}
result () ;
}
void result ()
{
system("cls") ;
cout << "The total of question is :" << question_num << endl ;
cout << "The correct answer from you is :" << correct << endl ;
cout << "The wrong answer from you is :" << wrong << endl ;
}
void question (string question , string a , string b , string c , string d , char correct_answer)
{
cout << question << endl ;
cout << "A. \t" << a << endl ;
cout << "B. \t" << b << endl ;
cout << "C. \t" << c << endl ;
cout << "D. \t" << d << endl ;
char answer ;
cout << "Please enter your answer here :" ;
cin>>answer ;
if (answer == correct_answer)
{
correct ++;
}
else
wrong ++ ;
question_num ++ ;
quiz_count() ;
}
【问题讨论】:
-
您会很高兴听到您不需要任何人的帮助来解决这个问题,只需一个您已经拥有的工具:您的调试器!这正是调试器的用途。 runs your program, one line at a time, and shows you what's happening,这是每个 C++ 开发人员都必须知道的事情。在调试器的帮助下,您将能够快速找到此程序以及您编写的所有未来程序中的所有问题,而无需向任何人寻求帮助。您是否已经尝试过使用调试器?如果不是,为什么不呢?您的调试器向您展示了什么?
-
display_question递归调用自身:display_question调用question调用quiz_count调用display_question。对display_question的每个嵌套调用都会重新开始循环。最有可能的是,您只想放弃来自quiz_count的display_question呼叫
标签: c++ loops for-loop switch-statement case