How to fix an error in my code?

4 次查看(过去 30 天)
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 个)

Walter Roberson
Walter Roberson 2022-5-1
if strcmp(arith_operator, '+')
  1 个评论
Mayada Almousa
Mayada Almousa 2022-5-1
I try it and when I run the code and choose + the condition dosen't work

请先登录,再进行评论。


Torsten
Torsten 2022-5-1
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 个评论
Torsten
Torsten 2022-5-2
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
Walter Roberson 2022-5-2
Using == is going to lead to trouble if the user enters more than one character.

请先登录,再进行评论。


Image Analyst
Image Analyst 2022-5-1
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 个评论
Mayada Almousa
Mayada Almousa 2022-5-1
Thanks for your help but it desen't work
Image Analyst
Image Analyst 2022-5-2
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by