How to write a script for the following?

1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
The script should iterate from 1 to 9 to produce the expressions on the left, then perform the specified operation to get the results on the right, and finally print exactly in the format above
Thank you!

 採用された回答

Stephen23
Stephen23 2017 年 11 月 4 日

0 投票

>> for k=1:9, n=sscanf(sprintf('%d',1:k),'%d'); fprintf('%d x 8 + %d = %d\n',n,k,n*8+k); end
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
>>

5 件のコメント

Zhuoying Lin
Zhuoying Lin 2017 年 11 月 4 日
Thank you! Yet I haven't learned sscanf
Stephen23
Stephen23 2017 年 11 月 4 日
編集済み: Stephen23 2017 年 11 月 4 日
You can learn about sscanf by reading the MATLAB documentation:
Alternatively you can simply replace sscanf with str2double:
>> for k=1:9, n=str2double(sprintf('%d',1:k)); fprintf('%d x 8 + %d = %d\n',n,k,n*8+k); end
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
Remember to accept the answer that best resolves your question!
Zhuoying Lin
Zhuoying Lin 2017 年 11 月 4 日
Is there any other way to do it if I don't use or sscanf or str2double?
Stephen23
Stephen23 2017 年 11 月 4 日
編集済み: Stephen23 2017 年 11 月 4 日
@Zhuoying Lin: of course, there are always other ways of doing things. You could calculate n without any strings at all, which might even be more efficient:
n = sum((k:-1:1).*10.^(0:k-1));
e.g.
>> for k=1:9, n=sum((k:-1:1).*10.^(0:k-1)); fprintf('%d x 8 + %d = %d\n',n,k,n*8+k); end
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
Zhuoying Lin
Zhuoying Lin 2017 年 11 月 4 日
Okay!Thank you very much!

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 11 月 4 日

0 投票

for loop and use fprintf()

1 件のコメント

Zhuoying Lin
Zhuoying Lin 2017 年 11 月 4 日
Yes I know what it is tested on but I have no idea how to compose it

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

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by