当我尝试使用递归时,我的C ++程序不起作用了什么?

时间:2011-06-03 00:54:16

标签: c++ recursion continue


我需要以下c ++代码的帮助,尝试在程序末尾添加continue,以便它为用户指定矩形尺寸,并要求用户重新重做该程序。

编译并在程序的最后部分没有愚蠢的if和else语句的情况下运行它,并且它可以工作。但随着continue /递归,它失败了。 LOLZ。我= noob。


int main()
{


    int height, width, tmp, tmp2;

    char continue;

    cout << "Please Enter The Height Of A Rectangle (whole numbers only): ";
height:
    cin >> height;
    if(height<1)
    {
        cout << "   Please Enter A Height Of Between 1 And 20: ";
        goto height;
    }
    cout << "Please Enter The Width Of A Rectangle  (whole numbers only): ";
width:
    cin >> width;
    if(width<1)
    {
        cout << "   Please Enter A Width Of Between 1 And 38: ";
        goto width;
    }

    cout << ' ';                                         // Add a space at the start (to neaten top)
    for(tmp=0; tmp!=width; tmp++) cout << "__";          // Top Of Rectangle
    for(tmp=0; tmp!=(height-1); tmp++)
    {
        cout << "\n|";   // Left Side Of Rectangle
        for(tmp2=0; tmp2!=width; tmp2++) cout << "  ";    // Create A Gap Between Sides
        cout << "|";
    }                                  // Right Side Of Rectangle
    cout << "\n|";                                       // Left Side Of Bottom Of Rectangle  to neaten bottom)
    for(tmp=0; tmp!=width; tmp++) cout << "__";          // Bottom Of Rectangle
    cout << '|';                                         // Right Side Of Bottom Of Rectangle (to neaten bottom)

    cout << "Type 'y' if you would like to continue and any other combination to quit.";
continue:
    cin >> continue;
    if(continue == 'y')
    {
        main();
        cout << "\n\n";
        system("PAUSE");
        return 0;
    }
    else
        cout << "\n\n";
    system("PAUSE");
    return 0;
}

6 个答案:

答案 0 :(得分:5)

continue是C ++中的关键字,因此您不能拥有该名称的变量。

答案 1 :(得分:5)

你应该把你的代码放在一个while循环中。

int main()
{
    //  declaration of variables here

    do
    {
        // code here

        cout << "Type 'y' if you would like to continue and any other combination to quit.";
        cin >> doYouWantToContinue; // change the keyword!
    }
    while (doYouWantToContinue == 'y');
}

答案 2 :(得分:4)

除了continue是保留字之外,在C ++中调用main是违法的。从'03标准,§3.6.1/ 3:

  

函数main不得在程序中使用。 main的链接是实现定义的。声明maininlinestatic的程序格式不正确。名称main未另外保留。 [示例:成员函数,类和枚举可以被称为main,其他名称空间中的实体也可以被称为{{1}}。 ]

答案 3 :(得分:3)

continue用于短路循环,例如:

for (i = 0; i < 10; ++i)
{
    if (f(i))
    {
        continue; // skip the rest of the loop
    }

    do_something_interesting_with(i);
}

答案 4 :(得分:2)

continue是一个c ++关键字,使用不同的名称

而不是

char continue;

char cont;

答案 5 :(得分:0)

我的2¢:抛弃所有这些东西,并重写它,记住

  1. goto和标签不好;
  2. 他们应该用循环替换(在你的情况下可能是do ... while);
  3. 使用保留/已使用的名称声明变量/标签是不好的(在大多数情况下,它是非法的);
  4. main中的递归很糟糕(实际上,根据标准,这是非法的);
  5. 好的缩进不是可选的(即使编译器不介意)。
  6. #include可选。
  7. 也许可以将用户输入/验证逻辑移到单独的函数中以避免代码重复。