Why does the code return an additional answer value that I have not asked for?
1 回表示 (過去 30 日間)
古いコメントを表示
First I defined a function:
function [p,q] = quadratic_formula(a, b, c)
p = (-b + sqrt((b)^2-4*a*c))/(2*a)
q = (-b - sqrt((b)^2-4*a*c))/(2*a)
end
After that I called the fuction with varying values. Every time it returns an answer value that I haven't asked for. For example,
quadratic_formula(5, 8, 3)
returns following:
p =
-0.6000
q =
-1
ans =
-0.6000
I don't want this answer value. Why does it return that equal to the value of 'p'?
0 件のコメント
回答 (2 件)
Davide Masiello
2022 年 10 月 20 日
編集済み: Davide Masiello
2022 年 10 月 20 日
That is because you call the function without assigning it to a variable.
Therefore Matlab assigns it to a variable called ans, which can accept only one value, i.e. the first one (or p in your case).
So, the first 2 values that appear are printed from within the function (because you didn't use semicolons).
Then it also shows ans because you also call the function without semicolons.
A better way of doing this in Matlab is
[p,q] = quadratic_formula(5, 8, 3)
function [p,q] = quadratic_formula(a, b, c)
p = (-b + sqrt((b)^2-4*a*c))/(2*a);
q = (-b - sqrt((b)^2-4*a*c))/(2*a);
end
0 件のコメント
Karen Yadira Lliguin León
2022 年 10 月 20 日
you need to put ';' at the end of the line to stop . Change these lines
p = (-b + sqrt((b)^2-4*a*c))/(2*a);
q = (-b - sqrt((b)^2-4*a*c))/(2*a);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!