Error when debugging problem
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Zaakir Essop
am 14 Mär. 2016
Kommentiert: Stephen23
am 14 Mär. 2016
Hi I have to debug the following code but I keep getting errors which i do not know how to fix.Any help will be greatfull :
clear
clc
Letters = {'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'W' 'X' 'Y' 'Z'};
ValueToConvert = input('Please enter the value you wish to express as a number: ');
ValueString = num2str(ValueToConvert);
Base = input('Please specify the base in which you wish to represent the value: ');
Remainders = [];
while ValueToConvert > 0
Value = 0;
while ValueToConvert >= Base
Value = Value + 1;
ValueToConvert = ValueToConvert - Base;
end
Remainders = [ValueToConvert Remainders];
Value = ValueToConvert;
clear Value Remainders
end
Number = '';
for count = 1:1:size(Remainders,2)
if Remainders(count) <= 10
Number = [Number Num2Str(Remainders(count))];
else
Number = [Number Letters(Remainders(count) - 9)];
end
end
disp(['The value ' ValueString ' is expressed by the number ' Number ' in the base-' Base ' number system.'])
Im getting the following error:
Please enter the value you wish to express as a number: 766
Please specify the base in which you wish to represent the value: 16
* _error: 'Remainders' undefined near line 18 column 31
error: called from
Tutorial6Broken at line 18 column 13_*
Thanks
0 Kommentare
Akzeptierte Antwort
Stephen23
am 14 Mär. 2016
Bearbeitet: Stephen23
am 14 Mär. 2016
For no obvious reason you clear some variables using this line:
clear Value Remainders
and then expect to be able to refer to those variables again. Thus the error.
Once you clear a variable it does not exist. If it does not exist how do you expect to be able to refer to it on this line?:
Remainders = [ValueToConvert Remainders];
Although beginners love using clear everywhere it usually serves no purpose at all, and in your case just broke your code. Avoid sticking clear everywhere. This is cargo-cult programming.
3 Kommentare
Stephen23
am 14 Mär. 2016
Obviously your condition is never met, so the loop never finishes. Try displaying the value of ValueToConvert at the end of each while loop. Check out the values and decide why it does not meet the conditions for ending the loop.
You should also learn to use the debugging tools.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!