在'else'之前预期的primary-expression

时间:2011-02-07 03:47:07

标签: c++

我在这里遇到紧急情况。我的CP 1课程将在明天完成这项功课。我们必须做一个简单的骰子游戏。如果你得到相同数量的双打,那么好事就会发生。这是功能:

void Doubles();       //prototype for the function Doubles()
//pre: n/a
//post: Plays a simple dice game with the user

void Doubles()
{
    //variables declared to store dice values
    int DieOne, DieTwo, PlayerSame, ComputerSame;

    cout<<"\nLET'S PLAY DOUBLES!!!\n"<<endl;
    srand ( time(NULL) );         //initialize random seed

    DieOne = rand()%6 + 1;
    DieTwo = rand()%6 + 1;

    cout<<"\nYour first die is a "<<DieOne;
    cout<<"\nYour second die is a "<<DieTwo;
    if(DieOne == DieTwo)
    {
       PlayerSame = 1;
    }
    else
    {
        PlayerSame = 0;
    }

    DieOne = rand()%6 + 1;
    DieTwo = rand()%6 + 1;

    cout<<"\n\nThe computer's first die is a "<<DieOne;
    cout<<"\nThe computer's second die is a "<<DieTwo;
    if(DieOne == DieTwo)
    {
        ComputerSame = 1;
    }
    else
    {
        ComputerSame = 0;
    }

    if(PlayerSame == 1 && ComputerSame == 0)
    {
        cout<<"\n\nYou win! Your dice are the same and the "
            <<"computer's dice aren't!";
    }
        else if(PlayerSame == 1 && ComputerSame == 1)
        {
            cout<<"\n\nYou tied! Your dice are the same and the "
                <<"computer's dice are the same!";
        }
        else if(PlayerSame == 0 && ComputerSame == 1)
        {
            cout<<"\n\nYou lost! Your dice are not the same, and the "
                <<"computer's dice are!";
    else
    {
        cout<<"\n\nNeither you nor the computer had dice that matched, "
            <<"so you both lose!";
    }
}

那么为什么,我运行这个,我是否在标题中声明了编译器错误?主要表达就在那里!它所指的“其他”是那里的最后一个。非常感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

你在第二个else if

之后忘记了块的右括号

答案 1 :(得分:2)

正如已经指出的那样,你缺少支撑,但是缺陷来自于无法正确查看代码缩进而无法清楚地看到错误。 else if上的缩进比if缩进了一次,如果不是这样的话,你会很快看到缺少的大括号,但是,如格式化的那样,它更容易被遗漏,尽管我甚至没有阅读整个帖子在查看代码并自己发现丢失的大括号之前(我有很多遗留代码,我保留了很多缩进,我已经修复了多年,这是导致这个特定问题的常见格式错误类型。正确的格式化将导致更快地发现这种类型的错误,特别是在程序员长时间没有编程的情况下,并且在查看代码细节之前没有经验丰富地修复他们头脑中的格式。

答案 2 :(得分:1)

}行之后,您似乎错过了大括号<<"computer's dice are!";

你的编译器不会告诉你它看到错误的行号吗?

答案 3 :(得分:1)

PLease在else之前添加右括号。

else if(PlayerSame == 0 && ComputerSame == 1)
{
    cout<<"\n\nYou lost! Your dice are not the same, and the "
        <<"computer's dice are!";

}
    else
    {
        cout<<"\n\nNeither you nor the computer had dice that matched, "
            <<"so you both lose!";
    }