如何在c++中循环回到开头

How do I loop back to the beginning in c++

本文关键字:开头 循环 c++      更新时间:2023-10-16

我最近开始用c++编程,所以对于我的程序,当用户说"是"时,我需要循环回到开始,当用户说"否"时,我需要结束程序。我在想怎么才能回到开头?

#include <iostream>
using namespace std;
int main() {
    int x;
    int y;
    char yes, no, answer;
    {
        cout << "Please enter a number for the x coordinate" << endl;
        cin >> x;
        cout << "Please enter a number for the y coordinate" << endl;
        cin >> y;
        if (x == 0) {
            if (y == 0)
                cout << "you are on the origin" << endl;
            else
                cout << "you are on the y axis" << endl;
        }
        else if (x > 0) {
            if (y == 0)
                cout << "you are on the x coordinate" << endl;
            else if (y > 0)
                cout << "you are in the 1st quadrant" << endl;
            else
                cout << "you are in the 4th qaudrant" << endl;
        }
        else if (x < 0) {
            if (y > 0)
                cout << "you are in the 2nd quadrant" << endl;
            else if (y < 0)
                cout << "you are in the 3rd quadrant" << endl;
        }
        cout << "Do you want to run the program again either types yes or no" << endl;
        cin >> answer;
        if (answer == 'yes' || answer == 'Yes')
            system("pause");
    }
}

可以将代码放入循环中:

while(true) {
     ... (existing code goes here)
     if (answer != 'yes' && answer != 'Yes')
         break;
}