Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 26 Okt. 2022
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'

Weitere Antworten (0)

Kategorien

Mehr zu Interactive Control and Callbacks finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by