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!

Answers (3)

if strcmp(arith_operator, '+')

1 Comment

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

Sign in to comment.

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 Comments

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.

Sign in to comment.

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 Comments

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.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2021b

Asked:

on 1 May 2022

Commented:

on 2 May 2022

Community Treasure Hunt

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

Start Hunting!