How to fix an error in my code?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (3)
Torsten
il 1 Mag 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 Commenti
Torsten
il 2 Mag 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
il 2 Mag 2022
Using == is going to lead to trouble if the user enters more than one character.
Image Analyst
il 1 Mag 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 Commenti
Image Analyst
il 2 Mag 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.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
