decimal place and ans problem

1 view (last 30 days)
Daniel Siwiec
Daniel Siwiec on 29 Nov 2015
Commented: Jan on 29 Nov 2015
So i have write a script but i still have 2 problems; *First one is that the result shuld be shown with 5 numbers after coma and i have no idea how to to this. *The second one is with ans, i got it twice after running my script and i got no idea why, can someone expalin me why did i get this and how to get rid out of it?
Here is my script:
clc
disp('Program liczący miejsca zerowe funkcji kwadratowej - Daniel Siwiec')
disp('ax^2+bx+c=0')
a=input('podaj wartość a:');
b=input('podaj wartość b:');
c=input('podaj wartość c:');
if a==0&&b==0&&c==0
disp('równanie tożsamościowe')
disp('równanie ma nieskończenie wiele rozwiązań')
elseif a==0&&b==0&&c~=0
disp('równanie sprzeczne')
disp('równanie nie ma rozwiązania')
elseif a==0&&b~=0&&c~=0
disp('równanie liniowe')
disp('równanie ma 1 rozwiązanie')
disp([c])
else a~=0&&b~=0&&c~=0
disp('równanie kwadratowe')
end
if a~=0&&b~=0&&c~=0
delta=b^2-4*a*c
if delta<0
disp('równanie nie ma rozwiązania')
elseif delta==0
disp ('równanie ma 1 rozwiązanie')
x0=-b/(2*a)
else delta>0
disp('równanie ma 2 rozwiązania')
x1 = (-b-sqrt(delta))/(2*a);
x2 = (-b+sqrt(delta))/(2*a);
disp([x1,x2])
end
end
and the result is
  1 Comment
Jan
Jan on 29 Nov 2015
Do you see that your code is not readable and that code is nicely formatted in other questions? Please use the "{} Code" button for a proper code formatting.

Sign in to comment.

Answers (1)

Jan
Jan on 29 Nov 2015
The ans appears, when a line of code is not terminated by a semicolon.
The number of shown decimals is controlled either generally by the format command. See:
doc format
format short g
You can control the output with more options if you use fprintf:
fprintf('%14.4f', pi)
As usual I suggest to read the Getting Started chapters in the documentation, which explain the basics very efficiently.
  2 Comments
Daniel Siwiec
Daniel Siwiec on 29 Nov 2015
So I manage the ans problem but i don't get how to use doc format format short g where shuld i put this in the code?
Jan
Jan on 29 Nov 2015
Type in "doc format" in the command line to find out, how to use the format command.
But I suggest to replace
disp([x1,x2])
by
fprintf('%.5f %.5f\n', x1, x2);

Sign in to comment.

Categories

Find more on Get Started with Optimization Toolbox in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!