How to count digits of a number in easy way?
15 views (last 30 days)
Show older comments
Hi first of all I am a beginner :D
I don't know much about matlab.
I want to know how can you count digits of a number in matlab in an easy way.
i found this :
A=input('enter a number');
max(ceil(log10(abs(A))),1)
But I'm not allowed to use it.
It should be easy and should containing while,if,...
I have tried myself:
clc
x=input('Enter Number A= ');
t=0;
x=x/10;
t=t+1;
while x<0
if x>0
x=x/10;
t=t+1;
end
end
disp(t)
__________
But it won't work!
can you guys please help me?
by the way the question I want to write the code for it is input 7 numbers then count digits of them and show.
thankssss a lot
3 Comments
Answers (2)
Jan
on 22 May 2018
Edited: Jan
on 22 May 2018
Of course log10 is the perfect method. That you are "not allowed to use it" sounds like one of the typical homework questions, when teachers try to force students to find solutions apart from the obvious and efficient built-in methods. As soon as your schooling is finished, this will be completely useless. So keep in mind, that log10 is the best solution. An now try it with a wooden hammer...
while x<0
if x>0
This cannot work. Do you mean positive numbers? Then you can run a loop like "while x > 1".
x = input('Enter Number A= ');
t = 0;
while x > 1
x = x / 10
t = t + 1
end
disp(t)
I've only removed some lines from your code. What do you observe? Do you need to adjust some parameters? Try it with 1, 2, 9, 10, 11, 99, 100, 101 and so on.
Note, that I have have not written a solution of your homework (it would be cheating to submit it), but that I've taken all lines from your suggestion and just changed "< 0" to "> 1".
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!