c - 修复在 'else' 之前出现的错误预期表达式的代码

标签 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);
}

最佳答案

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

if(condition); { block; }

C 将其解释为:检查条件,无论结果如何总是执行 block

(2+3) else 条件错误且无意义:如果到达 elsesum != 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 :-)

希望一切都清楚

关于c - 修复在 'else' 之前出现的错误预期表达式的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183201/

相关文章:

c - 如何在 C 中模拟构造函数或静态 block

c - 宏解析地址

mysql - 将 mysql.h 路径传递给 gcc 编译器

c - RSA Authentication Agent API 文档中的函数签名是否正确?

c - 从apache模块读取POST参数

c - 为什么字符串 "exist"和字符内存与字符串内存不同?

c - 使用 C 为日历控制台应用程序添加选项卡

c - 在UDP服务器编程中如何将传入的udp客户端与套接字绑定(bind)?

c - 如何在 Linux 内核中创建一个全局可访问的结构

c - clear_page_c 的作用是什么?