필터 지우기
필터 지우기

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