My program to calculate roots works incorrectly?

I have the user input a, b, and c (of a quadratic equation) into a dialog box. the discriminate is calculated and if it's greater than 0, it should output "two roots", less than 0 "no roots", etc. However, everything I enter returns "no roots"
prompt={'enter a: ','Enter b: ','Enter c: '};
dlg_title='quadratic';
answer=inputdlg(prompt,dlg_title);
a = (answer{1});
b = (answer{2});
c = (answer{3});
D = b^2 - 4.*a.*c;
p = [a b c];
if D>0
disp('There are two roots')
r = roots(p)
elseif D<0
disp('There are no roots')
else
disp('There is one root')
r = roots(p)
end
any ideas how to fix it? I'm not very experience with matlab so I'm sure what I've done wrong.

 Accepted Answer

Your ‘answer’ variable is a cell array of strings. You have to liberate the numbers from their string representation:
a = str2num(answer{1});
b = str2num(answer{2});
c = str2num(answer{3});

6 Comments

I just tried that and it still isn't working :/
It works perfectly for me with the addition of str2num.
Example:
answer = [1,2,1]
There is one root
r =
-1.0000e+000
-1.0000e+000
answer = [1,3,2]
There are two roots
r =
-2.0000e+000
-1.0000e+000
answer = [1,2,3]
There are no roots
Enter the values for ‘answer’ in the input dialogue and you should get the same results as I did.
Okay I made a change that I forgot to switch back before I tried and those worked for mine too, thank you!!
My pleasure!
Say ‘Hi!’ to Kayla for me, too!
Someone who seemed to be working on exactly the same problem as you were. Thought you might have been classmates.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!