【问题标题】:The PERSISTENT declaration must precede any use of the variablePERSISTENT 声明必须在变量的任何使用之前
【发布时间】:2019-03-01 00:49:05
【问题描述】:

在做 matlab 作业时,我遇到了一个非常奇怪的错误。这是我的代码:

function [z,times] = Divide(x,y)

    persistent times;

    if (y == 0)
        if (isempty(times))
            times = 1;
        else
            times = times + 1;
        end
    end

    z = x/y;
end

运行时,这给了我错误:

Error: File: Divide.m Line: 3 Column: 16
The PERSISTENT declaration must precede any use of the variable times.

这很奇怪,因为它告诉我需要在将变量声明为持久变量之前将其声明为持久变量(!?)。我不知道我在这里做错了什么,所以如果我应该使用一些奇怪的解决方法,请告诉我。

【问题讨论】:

    标签: matlab compiler-errors persistent


    【解决方案1】:

    错误消息的意思是:在将其声明为持久变量之前,您已经使用了“时间”。正如您在返回变量中使用“时间”一样。

    一种解决方案可能是为“时间”保留两个不同的变量,一个用于持久变量,另一个用于返回变量。

    在此处粘贴我的更改以供参考。祝你好运!

    function [z,times] = Divide(x,y)
        persistent p_times;
    
        if (y == 0)
            if (isempty(p_times))
                p_times = 1;
            else
                p_times = p_times + 1;
            end
        end
    
        times = p_times;
        z = x/y;
    end
    

    【讨论】:

    • 优秀的答案!欢迎来到 SO!
    • 哦,呃,我是个白痴。在函数的输出中引用变量需要已经声明它们,这有点奇怪。我对这种语言还不够习惯哈哈
    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2012-10-17
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多