Function returns ans, how to exclude?

1 回表示 (過去 30 日間)
Sveinar Bjørnseth
Sveinar Bjørnseth 2020 年 10 月 7 日
編集済み: Stephen23 2020 年 10 月 8 日
Good evening,
I am trying to write a script that returns 2 answer for the quadratic equation.
And I want to be able to input whatever values for a,b,c I want.
I have written this in the script:
function [x1,x2] = quad_equation(a,b,c)
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a)
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a)
end
It runs fine, but it outputs with "ans" at the end, and I can't figure out how to get rid of it.
Output:
x1 =
1
x2 =
-4
ans =
1
Any suggestions? :)
  1 件のコメント
Stephen23
Stephen23 2020 年 10 月 8 日
編集済み: Stephen23 2020 年 10 月 8 日
What is the point in defining a fucntion with three input arguments, which are then totally ignored?
function [x1,x2] = quad_equation(a,b,c)
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
Get rid of all of those input calls, input makes functions untestable, unrepeatable, ungeneralizable, unexpandable.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 10 月 7 日
Change
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a)
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a)
to
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a);
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a);
Then, when you run your function, be sure to assign the results to variables, and be sure to put a semi-colon at the end of the line:
[first, second] = quad_equation(83,-5,-9);

madhan ravi
madhan ravi 2020 年 10 月 7 日
[x1, x2] = quad_equation
function [x1, x2] = quad_equation
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a);
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a);
end

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by