Error when debugging problem

조회 수: 1 (최근 30일)
Zaakir  Essop
Zaakir Essop 2016년 3월 14일
댓글: Stephen23 2016년 3월 14일
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

채택된 답변

Stephen23
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
Zaakir  Essop
Zaakir Essop 2016년 3월 14일
If I remove the 'clear...' it goes into an infinite loop
Stephen23
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by