How to display the results of a for loop

63 ビュー (過去 30 日間)
Jesse Schultz
Jesse Schultz 2019 年 9 月 10 日
編集済み: Walter Roberson 2023 年 7 月 26 日
I want to make a game of 21, that starts with the user getting two random cards and then printing out what they get, using a for loop keeps saying "Index exceeds the number of array elements(1)."
my code is
for i =1:2
card = randi([0 10]);
if (card ==0)
card = 'A'; %if the result is 0, rename it to A
end
end
fprintf("You have been given 2 cards, %d and %d" , card(i))
  1 件のコメント
Stephen23
Stephen23 2019 年 9 月 10 日
編集済み: Stephen23 2019 年 9 月 10 日
This defines a scalar numeric (an integer from 0 and 10, inclusive), which you name card:
card = randi([0 10])
Your code does not do anything that changes the size of card., or allocate/concatenate/etc it into any other variable. On each loop iteration you redefine card as a new scalar.
Then after the loop (whose last iteration defines i=2) you use this code:
card(i)
card only has one element (you defined it to be scalar), but you are trying to access its 2nd element. Thus the error.

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

回答 (1 件)

Urmila Rajpurohith
Urmila Rajpurohith 2019 年 9 月 13 日
As mentioned above the variable “card” is a scalar.
To display the results of for loop you can create a Null vector and append the card value to the vector and while printing the output you can print the vector.
result=[];
for i =1:2
card = randi([0 10])
if (card ==0)
card = 'A'; %if the result is 0, rename it to A
end
result=[result card];
end
fprintf("You have been given 2 cards, %d %d", result);
  2 件のコメント
GAGANDEEP KAUR SIDHU
GAGANDEEP KAUR SIDHU 2023 年 7 月 26 日
編集済み: Walter Roberson 2023 年 7 月 26 日
result=[];
for i =1:2
card = randi([0 10])
if (card ==0)
card = 'A'; %if the result is 0, rename it to A
end
result=[result card];
end
fprintf("You have been given 2 cards, %d %d", result);
Walter Roberson
Walter Roberson 2023 年 7 月 26 日
編集済み: Walter Roberson 2023 年 7 月 26 日
Suppose 0 is randomly generated, and then (for example) 8. Then the sequence would go
result = []
result = []
card = 0 %assumption for testing
card = 0
card = 'A' %because of if test
card = 'A'
result = [result card]
result = 'A'
card = 8 %assumption for testing
card = 8
result = [result card]
result = ''
Where is the output ?
fprintf("You have been given 2 cards, %d %d", result);
You have been given 2 cards, 65 8
Okay, I see the 8 there, but what is the 65 ?

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

カテゴリ

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