简体   繁体   中英

How do I fix this error: “Undefined function or variable 'NaN'”?

I'm getting an error message in the yellow highlighted region that says "Undefined function or variable 'NaN'".

The purpose of this code is to determine the amount of change to give back to a customer. This is based on how much an item costs and how much was paid. Also, the code should return a flag saying if the transaction was completed.

This isn't all of my code, but I didn't want to make this longer than necessary.

Can anyone tell me what's wrong?


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

I couldn't confirm the problem with 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

I would recommend reformatting your code to the following:

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

By refactoring, you save yourself some needless comparisons, assignments, and logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM