How to fix an error in my code?
3 views (last 30 days)
Show older comments
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!
0 Comments
Answers (3)
Torsten
on 1 May 2022
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
Torsten
on 2 May 2022
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
Walter Roberson
on 2 May 2022
Using == is going to lead to trouble if the user enters more than one character.
Image Analyst
on 1 May 2022
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
Image Analyst
on 2 May 2022
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.
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!