How to fix an error in my code?

Hello everyone!
I hope ypu all good and healty
I write this code on a script file and MATLAB shows me that there is a mistake in the fifth line
This is the code:
function operator1=add(op1,op2)
op1=input('Enter an number:');
op2=input('Enter an number:');
arith_operator=input('Enter an operator:','s');
if arith_operator== +
operator1=op1+op2;
fprintf('ans=%i',operator1)
else
disp('Error!,Try again!')
end
end
MATLAB shows me that the mistake is in this line:
if arith_operator== +
I try to fix it but I don't know how
Please,if anyone here knows how to fix it,let me know how as soon as possible
Thank you all,have a great day!

回答(3 个)

if strcmp(arith_operator, '+')

1 个评论

I try it and when I run the code and choose + the condition dosen't work

请先登录,再进行评论。

Works for me:
op1=input('Enter an number:');
op2=input('Enter an number:');
arith_operator=input('Enter an operator:','s');
if arith_operator== '+'
operator1=op1+op2;
fprintf('ans=%i',operator1)
else
disp('Error!,Try again!')
end

3 个评论

but you didn't use any function,in my project I should use function:(
operator1 = add();
function operator1=add()
op1=input('Enter an number:');
op2=input('Enter an number:');
arith_operator=input('Enter an operator:','s');
if arith_operator== '+'
operator1=op1+op2;
fprintf('ans=%i',operator1)
else
operator1 = NaN;
disp('Error!,Try again!')
end
end
Using == is going to lead to trouble if the user enters more than one character.

请先登录,再进行评论。

This works fine. Put all this into one m-file:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
markerSize = 40;
result = add(1, 2);
function operator1 = add(op1, op2)
% Ignore incoming op1 and op2 and ask for new ones.
op1=input('Enter an integer:');
op2=input('Enter an integer:');
arith_operator=input('Enter an operator:','s');
if strcmp(arith_operator, '+')
operator1 = op1 + op2;
fprintf('\nThe result = %d.\n', operator1)
else
message = sprintf('Error!\nYou need to enter a plus sign!\nTry replacing user and try again!');
uiwait(warndlg(message))
end
end

2 个评论

Thanks for your help but it desen't work
Did you hit Enter after you typed +?
It definitely works. I just tried it again and it works.
Enter an integer:8
Enter an integer:9
Enter an operator:+
The result = 17.
>>
I'm attaching the actual m-file I used. Don't alter it -- just run it.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

产品

版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by