The program cannot work

2 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 7 月 4 日
コメント済み: Shuoze Xu 2022 年 7 月 5 日
Hi.
There is a review question without answer.
Here is the question
A function is defined as
function [dice] = roll(sides)
dice(0) = randi(sides);
dice(1) = randi(sides);
end
If the function is called as follows:
[roll1,roll2] = dice(6);
and the random numbers generated are 1 and 6. What will be the value od roll1 and roll2?
My first question is that what is roll1 and roll2? i confused for the function. the return value is only one, why it can be returned two values as roll1 and roll2 ?
Then, the function name is roll, why use dice to call the function?
Thank you all.

採用された回答

Siraj
Siraj 2022 年 7 月 4 日
編集済み: Siraj 2022 年 7 月 4 日
Hi,
It is my understanding that you want to know the value of roll1 and roll2,
“[roll1, roll2] = dice (6)”.
This will lead to an “Too many output arguments” error because the function has only one return object that is “dice”.
The name of the function is “roll” therefore we cannot call the function using “dice()”.
The correct way to call the function is “d = roll(6) “ where “d” is a random integer array of dimension 1X2 and values in range 1 to 6.
For further help you can see functions in MATLAB.
d = roll(6)
d = 1×2
3 2
function [dice] = roll(sides)
dice(1) = randi(sides);
dice(2) = randi(sides);
end
  1 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 7 月 5 日
Thanks.

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

その他の回答 (1 件)

Chunru
Chunru 2022 年 7 月 4 日
編集済み: Chunru 2022 年 7 月 4 日
% [roll1,roll2] = dice(6)
% The above is wrong in syntax as the function has only ONE return object
% dice (as an array).
% The correct way to call the function
d = roll(6)
d = 2×1
4 3
function [dice] = roll(sides)
% dice(0) = randi(sides);
% dice(1) = randi(sides);
dice = randi([1 6], [2 1]); % generate 2x1 random integer in range [1 6]
end
  1 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 7 月 5 日
Thank you.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by