修复它出现的代码,说'else'之前的错误预期表达式

时间:2016-05-12 09:46:05

标签: c

else语句出错,并且应该在它之前发生一些事情。 我真的不知道什么是错的。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int random1_6()
{
    return ((rand() % 6) + 1);
}

int main(void)
{
    int a, b, c, d, equal, sum;
    srand(time(NULL));
    a = random1_6();
    b=random1_6();
    sum = a + b;
    printf("\n The player rolled: %d + %d = %d. \n the players point is %d. \n", a, b, sum, sum);
    if (sum ==7);
    {
        printf("The player wins. \n");
    }
    else (sum !=7); 
    {
        c = random1_6();
        d=random1_6();
        equal = c + d;     
        printf("\n The player rolled: %d + %d = %d", c, d, equal);
}

3 个答案:

答案 0 :(得分:0)

(1)您不必在;之后放置if。如果你写:

if(condition); { block; }

C将其解释为:检查condition,无论结果如何,始终执行block

(2 + 3)else条件错误且无意义:如果您到达else,则sum != 7始终为真,因此无需检查它。

在任何情况下,如果您需要,正确的语法是:

}
else if(sum != 7) 
{

使用if且没有;

(4)您也忘记从main函数返回一些内容,声明为返回int值。

(5)在您的代码中,最终}丢失了,可能只是错误的副本和粘贴?

以下是具有上述更正的代码:

int random1_6()
{
    // enter code here
    return ((rand() % 6) + 1);
}

int main(void)
{
    int a, b, c, d, equal, sum;

    srand(time(NULL));

    a = random1_6();
    b = random1_6();

    sum = a + b;

    printf("\n The player rolled: %d + %d = %d. \n the players point is %d. \n", a, b, sum, sum);

    if(sum == 7) // (1) Remove ";", it's wrong!
    {
       printf("The player wins. \n");
    } 
    else // (2) Remove "(sum !=7)", it's useless. (3) Remove ";" , it's wrong!
    // else if(sum != 7) // This is the correct sintax for an else if, just in case :-)
    {
        c = random1_6();
        d = random1_6();
        equal = c + d;     
        printf("\n The player rolled: %d + %d = %d", c, d, equal);
    }

    return 0; // (4) The function is declared returning an int, so you must return something.
} // (5) This bracket was missing :-)

希望一切都很清楚

答案 1 :(得分:-2)

你的其他陈述是错误的。 这是if else syn文本。

if (some-condition) {
} else{
}

或者您可以使用

if (some-condition) {
} else if (some-condition) {
}

只需删除(sum!= 7)您的代码即可。

答案 2 :(得分:-2)

删除不必要的分号。

if (sum == 7) {
 printf("The player wins. \n");
} else {
 c = random1_6();
 d = random1_6();
 equal = c + d; 
 printf("\n The player rolled: %d + %d = %d", c, d, equal);
}