Creating a loop for game

10 ビュー (過去 30 日間)
Sarah K
Sarah K 2019 年 10 月 22 日
編集済み: James Tursa 2019 年 10 月 22 日
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 件のコメント
James Tursa
James Tursa 2019 年 10 月 22 日
編集済み: James Tursa 2019 年 10 月 22 日
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.

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

回答 (1 件)

James Tursa
James Tursa 2019 年 10 月 22 日
編集済み: James Tursa 2019 年 10 月 22 日
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)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by