fprintf curiosity about incorrect value returned when string is assigned as a number.

1 次查看(过去 30 天)
Hello,
I am learning about fprintf and I was playing around. I ended up with this string below. I realize now that in the second sentence it should be %s because it's printing a string.
But! Here's my question. I don't get returned an error message. Instead, I get that 10 + 34 is 52.
WHY? I want to know.
N = 10; S = 34;
fprintf('What is %g plus %g? It''s %g! \n', N , S, num2str(N + S))
When I use fprintf('What is %g plus %g? It''s %s! \n', N , S, num2str(N + S)) I get 44 as expected.
Can anyone tell me why 52 is the number returned when the string is commanded as a number?

采纳的回答

Walter Roberson
Walter Roberson 2022-10-26
the sum is 44 and num2str(44) is '44' which is a character vector.
Every character is encoded as a 16 bit number, so the character vector '44' is encoded as pair of 16 bit numbers. The encoding for the digits 0 to 9 is integer 48 plus the digit value, so digit 4, '4' is encoded as 48+4 = 52. So you are passing in a vector of two values each of which happens to be 52 numerically, and the %g format would display the 52
If you looked closely you probably got an extra line
What is 52 plus
where it went to display the second '4'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by