如何修复此错误:“未定义的函数或变量'NaN'”?

时间:2015-09-16 02:26:47

标签: matlab loops

我在黄色突出显示的区域收到一条错误消息,上面写着“Undefined function or variable'NaN'”。

此代码的目的是确定回馈给客户的更改量。这取决于项目成本和支付的金额。此外,代码应返回一个标记,说明事务是否已完成。

这不是我的所有代码,但我不想让它超过必要的时间。

谁能告诉我什么是错的?

function [Change, flag] = makeChange(Cost, Paid)


extra = Paid-Cost;

if extra > 0
    Change = extra;    
    flag = true;
elseif extra == 0
    Change = 0;
    flag = true;
    return
else
   flag = false;
   Change = NaN;
   warning('That''s not enough to buy that item.');
   return

end

1 个答案:

答案 0 :(得分:0)

我无法通过Octave 3.8.1确认问题。

octave:1> makeChange.m
error: 'Paid' undefined near line 4 column 9
error: called from:
error:   /Path/to/makeChange.m at line 4, column 7
octave:1> Cost = 5
Cost =  5
octave:2> Paid = 10
Paid =  10
octave:3> [change, completed] = makeChange(Cost, Paid)
change =  5
completed =  1
octave:4> Cost = 10
Cost =  10
octave:5> Paid = 5
Paid =  5
octave:6> [change, completed] = makeChange(Cost, Paid)
warning: That's not enough to buy that item.
change = NaN
completed = 0

我建议您将代码重新格式化为以下内容:

function [Change, flag] = makeChange(Cost, Paid)

Change = Paid-Cost;
flag = true;

if Change < 0
   flag = false;
   Change = NaN;
   warning('That''s not enough to buy that item.');
   return
else
   return
end

通过重构,您可以节省一些不必要的比较,分配和逻辑。