showing unit using fprintf

11 ビュー (過去 30 日間)
Ysabelle Ngo
Ysabelle Ngo 2020 年 5 月 7 日
編集済み: Stephen23 2020 年 5 月 8 日
How can I use fprintf to show the unit cm without it looking like cm^2 ? I tried making unit=cm^2 but it just says cm is an unrecognized variable.
W = 0;
for i = 1:3
L = 1 ;
W = W+1 ;
A = (L*W);
unit = 1*(cm^2);
fprintf ('Length: %d\n', L)
fprintf ('Width: %d\n', W)
if L == W
disp ('The shape is square')
else
disp ('The shape is rectangle')
end
fprintf ('The area of the shape is: %.2f cm^2 \n', A)
disp (' ')
end

採用された回答

Stephen23
Stephen23 2020 年 5 月 7 日
編集済み: Stephen23 2020 年 5 月 8 日
fprintf and sprintf do not generate formatted text based on markup (like LaTeX or XML). Their output is pure text, and pure text does not store any formatting information at all (no color, no size, no typeface, no superscript, etc.). Pure text is just characters in a row, it is entirely up to the displaying application to decide how they should look like.
But luckily for you, one of the characters Unicode supports is "Superscript Two" (U+00B2), and because (recent versions of) MATLAB use Unicode to represent text characters, this character is easy to include in the fprintf format string using the \xH syntax given in the fprintf documentation:
>> fprintf('%.3f cm\xB2\n',pi)
3.142 cm²

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by