I need help displaying the max value in my while loop.

8 vues (au cours des 30 derniers jours)
Kevin Smith
Kevin Smith le 24 Sep 2017
So I have wrote this code for a while loop/string:
str=input('Enter an integer greater than 1:','s');
num=str2double(str);
cnt=0;
while num>1
cnt=cnt+1;
if mod(num,2)
num=num*3+1;
else
num=num/2;
end
end
s=cnt
It takes any given integer, multiplies it by 3 then adds 1 if it is odd. It divides the number by 2 when it is even. Also "s" represents the number of steps it takes for the loop to reach the end, which is when it reaches '1'. What I am having trouble with is figuring out how to display the max value reached during the loop.
Example, if the user enters "3" the steps would be 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
I need the output to be "The max value is 16."
I have tried different codes for "max" such as 'max(num)' and 'max(cnt)' but I cannot figure out how to display the highest value.
  1 commentaire
Stephen23
Stephen23 le 24 Sep 2017
Modifié(e) : Stephen23 le 24 Sep 2017
"So I have wrote this code..."
Really?! You wrote that code? Interestingly that code looks nothing like the code that you wrote, and exactly like the code that I gave you in my answer to your earlier question:
When you take someone's code you should:
  • accept their answer.
  • acknowledge that you did not write it.
Copying work and claiming it as your own is called plagiarism.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 24 Sep 2017
Modifié(e) : Walter Roberson le 24 Sep 2017
str=input('Enter an integer greater than 1:','s');
num=str2double(str);
cnt=0;
maxnum = num;
while num>1
cnt=cnt+1;
if mod(num,2)
num=num*3+1;
else
num=num/2;
end
if num > maxnum; maxnum = num; end
end
s=cnt
maxnum
  1 commentaire
Kevin Smith
Kevin Smith le 24 Sep 2017
Modifié(e) : Kevin Smith le 24 Sep 2017
Thanks for your help!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 24 Sep 2017
To " display the max value reached during the loop" you need to use fprintf(), assuming "during" means "inside". Here is your code with fprintf just before the bottom of the loop:
str=input('Enter an integer greater than 1:','s');
num=str2double(str);
iterationCount=0;
maxnum = num;
while num>1
iterationCount=iterationCount+1;
if mod(num,2)
num=num*3+1;
else
num=num/2;
end
if num > maxnum
maxnum = num;
end
fprintf('num = %d. The max after iteration #%d is %d\n', num, iterationCount, maxnum);
end

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by