Gnuplot中的'else if'逻辑语句

6
新版本的gnuplot (5.x) 有新的逻辑语法,但是我无法让 'else if' 语句工作。例如:
if(flag==1){
plot sin(x)
}
else{
plot cos(x)
}

可以工作,但是:

if(flag==1){
plot sin(x)
}
else if(flag==2){
plot cos(x)
}
else if(flag==3){
plot tan(x)
}

我尝试了很多{}的组合和'if'和'else'的放置位置,但都没有成功。有人知道如何在gnuplot 5.x中正确实现'else if'吗?

gnuplot指南(http://www.bersch.net/gnuplot-doc/if.html)没有使用'else if'的新逻辑语法示例,但有使用旧语法的示例,但我宁愿避免使用旧语法。


你可以避免在第二个例子中使用 else 并得到你需要的结果。 - Michael
1个回答

7
基于对Gnuplot最新版本中command.c源代码的简要检查,我认为该功能不受支持。更具体地说,相关部分可以在第1163行找到(见下文)。解析器首先确保后面是由括号包围的条件,然后如果接下来的标记是{,则激活新的语法,将整个if块隔离在一对匹配的{}中,并可选择查找后跟一个{}else,但其也允许只跟随一个与{}有关的子句。因此,一个简单的脚本如下:
if(flag == 1){
    print 1;
}else if(flag == 2){
    print 2;
}

确实会生成错误信息expected {else-clause}。一种解决办法是将if语句嵌套,如下:

if(flag == 1){

}else{
    if(flag == 2){

    }else{
        if(flag == 3){

        }
    }
}

可以承认,这样稍微啰嗦了一点...

void
if_command()
{
    double exprval;
    int end_token;

    if (!equals(++c_token, "("))    /* no expression */
    int_error(c_token, "expecting (expression)");
    exprval = real_expression();

    /*
     * EAM May 2011
     * New if {...} else {...} syntax can span multiple lines.
     * Isolate the active clause and execute it recursively.
     */
    if (equals(c_token,"{")) {
    /* Identify start and end position of the clause substring */
    char *clause = NULL;
    int if_start, if_end, else_start=0, else_end=0;
    int clause_start, clause_end;

    c_token = find_clause(&if_start, &if_end);

    if (equals(c_token,"else")) {
        if (!equals(++c_token,"{"))
        int_error(c_token,"expected {else-clause}");
        c_token = find_clause(&else_start, &else_end);
    }
    end_token = c_token;

    if (exprval != 0) {
        clause_start = if_start;
        clause_end = if_end;
        if_condition = TRUE;
    } else {
        clause_start = else_start;
        clause_end = else_end;
        if_condition = FALSE;
    }
    if_open_for_else = (else_start) ? FALSE : TRUE;

    if (if_condition || else_start != 0) {
        clause = new_clause(clause_start, clause_end);
        begin_clause();
        do_string_and_free(clause);
        end_clause();
    }

感谢您关注此事。很遗憾,“else if”的支持已经被取消了。我想在这种情况下,您的解决方法是最好的。 - Mead

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接