Creating a loop for game

4 visualizaciones (últimos 30 días)
Sarah K
Sarah K el 22 de Oct. de 2019
Editada: James Tursa el 22 de Oct. de 2019
I want to write a formula with a loop for a number game.
Criteria ...
This is my fnction so far...
function [output] = number_game(input)
% Creates a function for a number game for a scaler input
for output = 1:1:input
% Creates a loop that increments from 1 to the input number in increments of 1
disp(num2str(output));
output = output * 5
end
I am not sure if this is correct and how I do the "multiply 5 by the iteration number" stage.
How do I complete the function?
Apology, I am new to Matlab :)
  1 comentario
James Tursa
James Tursa el 22 de Oct. de 2019
Editada: James Tursa el 22 de Oct. de 2019
Don't replace your original code with edited code ... this practice makes it hard to follow any answers and comments.
In your latest edit, this line changes the loop counter variable "output" within the loop. Don't do that.
output = output * 5
Instead, simply display the value of output*5 ... you don't need to assign this value to anything.

Iniciar sesión para comentar.

Respuestas (1)

James Tursa
James Tursa el 22 de Oct. de 2019
Editada: James Tursa el 22 de Oct. de 2019
The name "input" is an existing MATLAB function. It would be best to change this to something else, e.g. n. And use a different variable name for the iterations than your function name, e.g., k.
function [output] = number_game(n)
% Creates a function for a number game for a scaler input
for k = 1:1:n
Then for the "multiply 5 by the iteration number" part, that is simply going to be 5*k. So that would be what you display. No need for the num2str conversion, the display function can handle numeric inputs.
I don't see any description of a required output, so you could probably delete that as well unless there is something else in the assignment that you haven't told us. E.g.
function number_game(n)

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by