Error when debugging problem
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2016-3-14
编辑:Stephen23
2016-3-14
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 个评论
Stephen23
2016-3-14
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!