How can I Write a function that takes as input two numbers, x and y, and outputs √xy if they have the same signs, x y if they have opposite signs, and 0 if either is zero

1 回表示 (過去 30 日間)
bob
bob 2020 年 3 月 9 日
回答済み: Image Analyst 2020 年 3 月 9 日
numbers=input('x','s');
if numbers(diff(sign(x(x~=0))))
disp('sqrt(x*y).')
elseif numbers isequal(sign(previous), sign(current))
disp('(x/y).')
elseif numbers~=0
disp('0.')
end
This is the code I tried but I ended up getting an error in the second line. What is going wrong with my code?
  2 件のコメント
Walter Roberson
Walter Roberson 2020 年 3 月 9 日
x does not exist. You assigned the input to numbers . Also you input as a character vector not as numeric.
Walter Roberson
Walter Roberson 2020 年 3 月 9 日
Hint: if the product is not positive then the result is the product, and otherwise is the square root of the product. The code becomes quite simple.

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

回答 (1 件)

Image Analyst
Image Analyst 2020 年 3 月 9 日
You need to convert the string you collected from the user into numbers using sscanf(). Try this:
usersInputString = input('Enter x y ', 's')
numbers = sscanf(usersInputString, '%f %f')
x = numbers(1)
y = numbers(2)
if sign(x) == sign(y)
fprintf('sqrt(x*y) = %f\n', sqrt(x*y))
etc.

カテゴリ

Help Center および File ExchangeCreate Model Web Views についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by