필터 지우기
필터 지우기

Not quite sure what I'm doing wrong for this calculator function problem

조회 수: 2 (최근 30일)
I have a project where I need to make a calculator that takes two input numbers and performs the operation (chosen by the user) on those numbers. I'm not sure what is going wrong with my code but when I tried calling the function like this:
result = kno20Calculator (5, 10, 'add')
I get the error message, "Matrix dimensions must agree". Also im aware there will probably be an issue with the log operation but I'll get around to that later. Here is my code:
function [result] = kno20Calculator(num1, num2, indicator) %#ok<*INUSD>
indicator = 'add'|'subtract'|'multiply'|'divide'|'exponent'|'lognum2(num1)'|'max'|'min';
if indicator == 'add'
result = num1 + num2;
elseif indicator == 'subtract'
result = num1 - num2;
elseif indicator == 'multiply'
result = num1 * num2;
elseif indicator == 'divide'
result = num1/num2;
elseif indicator == 'exponent'
result = num1^num2;
elseif indicator == 'lognum2(num1)'
result = lognum2(num1);
elseif indicator == 'max'
result = max(num1, num2);
elseif indicator == 'min'
result = min(num1, num2);
end
Thanks

채택된 답변

Geoff Hayes
Geoff Hayes 2018년 2월 11일
Kristen - when comparing strings, please use strcmp as you will get the error that you describe when you try to use the equality operator on two different sized character arrays. For example,
'hello' == 'goodbye'
generates the error.
Replace the == comparisons with
if strcmp(indicator,'add')
% do something
elseif strcmp(indicator,'subtract')
% etc.
endif
Do this for all of your conditions. Also, remove the second line of the function that seems to reinitialize the input parameter indicator to a string of all possible values.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by