How to write a while loop that returns the number of the value you put in?

1 回表示 (過去 30 日間)
Tess
Tess 2022 年 12 月 15 日
コメント済み: Image Analyst 2022 年 12 月 18 日
Hello, so the title might be confusing and i'll try to explain it better. I want to create a while loop so if the user put in the number let's say 4575, it'll return the number 4. Or 893 and itll return the number 3, 78 and itll return number 2 and so forth. Absolutely clueless on how to solve this honestly
  1 件のコメント
Stephen23
Stephen23 2022 年 12 月 15 日
編集済み: Stephen23 2022 年 12 月 15 日
"Absolutely clueless on how to solve this honestly"
Some people will tell you to convert to text, but the real solution is to use mathematics: what does LOG10 give you?
Try it, and show us what you come up with.

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2022 年 12 月 16 日
Have the user put in the number as a string with input
userInput = input('Enter your number : ', 's');
fprintf('Your number of %s is %d digits long.\n', userInput, length(userInput));
Not sure how a while loop comes into play. Do you want that in a while loop and keep asking them unless they type quit or something? Like this:
userInput = 'a';
while ~startsWith(userInput, 'Q', 'IgnoreCase',true)
userInput = input('Enter your number (Q to quit): ', 's');
if startsWith(userInput, 'Q', 'IgnoreCase',true)
break
end
fprintf('Your number of %s is %d digits long.\n', userInput, length(userInput));
end
  2 件のコメント
Tess
Tess 2022 年 12 月 18 日
ahhh i absolutely appreciate it, very helpful thank you !
Image Analyst
Image Analyst 2022 年 12 月 18 日
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2022 年 12 月 15 日
編集済み: Jan 2022 年 12 月 15 日
x = [4575, 893, 78, 12345];
y = floor(log10(x) + 1)
y = 1×4
4 3 2 5
Do you really need a loop?
x = 10000;
n = 0;
while x >= 1
n = n + 1;
x = x / 10;
end
n
n = 5
  3 件のコメント
Tess
Tess 2022 年 12 月 15 日
移動済み: Walter Roberson 2022 年 12 月 15 日
thank you, appreciate it man !
Walter Roberson
Walter Roberson 2022 年 12 月 15 日
Watch out for 0 and negative numbers.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by