如何在C++中只循环"continue"一次?

How to make a loop "continue" only once in C++?

本文关键字:continue 一次 循环 C++      更新时间:2023-10-16

我目前正在研究计算器,需要做一些我们没有教过的事情。在我讨论它是什么之前,我将发布下面的代码:

解决

int num1;
int num2;
char choice;
int answer;
char choice2;
bool MoveOn;
bool ActiveAnswer;
//  get first number
cout << "Enter your first number" << endl;
cin >> num1;
//  get an operator
//      is it valid?  if not, get another operator
while (MoveOn = true)
{
    cout << "What would you like to do? +, -, *, or / ?" << endl;
    //cout << "Press C to clear and start over or X to close the program" << endl;
    cin >> choice;

    if (choice == '+')
    {
        cout << "Enter your second number" << endl;        
        cin >> num2;        
        answer = num1 + num2;        
        cout << "The answer is: " << answer << endl;        
        MoveOn = true;        
        num1 = answer;
        cout << "Enter your second number" << endl;
        cin >> num2;
        answer = num1 + num2;
        cout << "The answer is: " << answer << endl;
    }
}
我需要做的是获取第一个数字,运算符,打印

出答案,向后移动并再次请求运算符,使用上一个答案作为第一个数字,获取第二个数字,再次打印答案。所以我需要的大部分工作。我花了一段时间才弄清楚如何让它再次使用以前的答案作为第一个数字,但随后出现了另一个问题。打印出第一个答案后,它会直接再次询问第二个数字,而不是让用户选择另一个运算符。我尝试的是有一个继续语句,但随后它会继续回到请求运算符,而不是让用户做第二个问题。我还尝试做两个单独的 if 语句,而不仅仅是你在上面看到的那个,但这也不起作用。我不是一个希望有人必须为我解决这个问题的人。我想了解发生了什么并知道它是如何工作的。如果有人能帮我一把,我将不胜感激。

您需要仔细查看您的代码并逐步完成它的功能。

现在的流程如下所示:

Ask for a number (num1)
(start_loop):
Ask for an operator
Ask for a second number (num2)
Calculate the answer (answer = num1 + num2)
Print the answer
**Ask for a second number (num2)**
Calculate the answer (answer = num1 + num2)
Print the answer
(go back to start_loop)

您两次要求第二个数字,这就是为什么您不会再次提示输入运算符的原因。没有必要在同一个循环中询问两次,因为计算机无论如何都会循环并重复您输入的第一个请求。

关键是只使用答案作为 num1。

(start_loop):
Ask for an operator
Ask for a second number (num2)
Calculate the answer (answer = num1 + num2)
Print the answer
Set the new first number to be the answer (num1 = answer)
(go back to start_loop)

如果您继续执行第二个请求,则还需要为下一个运算符添加请求,并再次重复整个块。这就是循环的目的 - 重复你的代码块,所以如果你开始在循环中看到重复的代码,这应该是一个危险信号,表明你做错了。

让循环为您重复代码。你的工作是弄清楚如何最好地编写重复的代码块,以及何时应该终止循环。

  • 如果您尝试终止程序,则应这样做。我认为您在上一条评论中做对了,但是您需要了解 while 循环和 for 循环的工作原理。它们会连续工作,除非你告诉它停止,你需要知道如何启动循环运行以及如何终止它。
  • 基本上没有 FALSE 语句,你的 while 循环不会终止,如果你输入或输入任何会改变 TRUE 语句的语句,那么它就会停止。
  • while 循环从其作用域内
  • 的第一行开始运行,一直运行到其作用域内的最后一行。在从第一行到最后一行重新开始之前,除非另有指示终止,否则将继续一次又一次地循环。
  • 因此,当您尝试终止程序时,不需要再次开始编写代码。
  • 所以这就是你应该如何终止程序;

       // Declare this variable on top of the function
       char terminate = 'W';
       // This will be placed at the bottom of your function
       cout << "Enter X to close the program, Otherwise Enter any key to continue" << endl;
       // The program has to be terminated by the user, Enter X to terminate
       // Otherwise, Enter any key to continue.
       cin >> terminate;
       if(terminate == 'X' || terminate == 'x')
       MoveOn = false;
       // Remember that char is case sensitive, X is different from x