필터 지우기
필터 지우기

fprintf Displays the wrong value

조회 수: 8 (최근 30일)
J
J 2014년 10월 22일
편집: J 2014년 10월 22일
The following command returns the wrong value when using the command:
fprintf('\ny = %1.2f\n\n',y);
Enter a value for x: 5
y = 45.00
y = 52.00
Here is the code:
clear all; clc
x = input('Enter a value for x: ');
if x == -2 || x == -6 || x == -4;
y = '3';
elseif x == 2;
y = '0';
else
error('Error');
end
clc
% display(y);
fprintf('\ny = %1.2f\n\n',y);

채택된 답변

Image Analyst
Image Analyst 2014년 10월 22일
편집: Image Analyst 2014년 10월 22일
You're setting y equal to a character string but using %1.2f (which doesn't make sense even if y were a double) instead of %s to display a character string. So it displays the ASCII values of the string. Instead of
y = '0'; % y is a character.
and so on, try
y = 0; % y is a double.
and use %d to display it, not %1.2f, in your fprintf() call.
  댓글 수: 1
J
J 2014년 10월 22일
I can't believe I missed that. Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Roger Stafford
Roger Stafford 2014년 10월 22일
You are assigning y string values, not numerical values, but you are displaying them using 'fprintf' for numerical values (%1.2f), so you have to expect strange results. For example the string value of y = '3' has a corresponding numerical value of 51.
Also you have written
if x == -2 x == -6 x == -4;
but that will not behave as I think you expect. Better read up on the 'if' function to see how to write a valid 'if' condition.
  댓글 수: 1
Image Analyst
Image Analyst 2014년 10월 22일
That's what I thought at first, but no, what he really needs to read is this http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup. I went ahead and formatted it properly so that the || show up now.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by