C++程序不会结束

C++ the program won't end

本文关键字:结束 程序 C++      更新时间:2023-10-16

你能说出错误是什么吗?它编译并运行良好,但程序不会结束。

我使用的是dev c++。代码为:

#include <iostream>
using namespace std;
main()
{
    char num;
again:
    int usr;
    float area;
    cout << "nEnter 1 to calculate area of rectanglen";
    cout << "Enter 2 to calculate area of trapezoidn";
    cout << "nEnter your choice: ";
    cin >> usr;
    if (usr == 1)
    {
        double width, length;
        cout << "Enter the width of rectangle: ";
        cin >> width;
        cout << "Enter the length of rectangle: ";
        cin >> length;
        area = length * width;
        cout << "The area of rectangle is: " << area;
    }
    if (usr == 2) {
        double base1, base2, height;
        cout << "Enter the base 1 of trapezoid: ";
        cin >> base1;
        cout << "Enter the base 2 of trapezoid: ";
        cin >> base2;
        cout << "Enter the height of trapezoid: ";
        cin >> height;
        area = (((base1 + base2) / 2) * height);
        cout << "The area of trapezoid is: " << area;
    }
    cout << "nndo you want to do another calculation?";
    cin >> num;
    {
        goto again;
    }
    if (num == 'y')
    {
        goto again;
    }
    if (num == 'n') {
        exit(0);
    }
}

永远不要使用goto,除非你有充分的理由(你没有)。

cin >> num;{
goto again;
}

我不知道你为什么写那个,但这就是问题所在。如果你用正确的格式写它,它会看起来像这个

cin >> num;
{
    goto again;
}

括号{}只是更改作用域(对变量等有用),但不做任何其他操作。goto again;仍然会被执行,所以您会陷入一个无休止的循环。

之后的两个条件都很好,所以只需删除{ goto again; }就可以"解决"您的问题。

删除代码中的第44行

您的代码

cin >> num;{
goto again;
 }

解决方案删除

再次转到

cin >> num;{
 }

这将解决您的问题