How do I call another function in the same file from the first function
5 次查看(过去 30 天)
显示 更早的评论
Hi.
That is my code.
% function file
function [p1,p2,Name1,Name2]= Playerpoint(point1,point2)
point1 = 10; % get the points
point2 = 15;
p1 = point1+10;
p2= point2 +10;
Name1 = name1;
Name2 = name2;
fprintf("The first user %s has %d points\n",Name1,p1);
fprintf("The second user has %d points\n",Name2,p2);
end
function [name1,name2] = Playername(n1,n2)
name1 = n1;
name2 = n2;
end
% driver file
n1 = input('Please enter the first user name: ','s'); % let players enter the names
n2 = input('Please enter the second user name: ','s');
[name1,name2] = Playername(n1,n2);
[p1,p2,Name1,Name2]= Playerpoint(point1,point2);
In my code, i try to create two players and let them get their inital points.
But there are bug Unrecognized function or variable 'name1'.
That is my expected result:
Please enter the first user name: abby
Please enter the second user name: bob
The first user abby has 20 points.
The second user bob has 25 points.
0 个评论
回答(1 个)
Harshal Ritwik
2023-6-16
编辑:Harshal Ritwik
2023-6-16
Hi,
As per my understanding you want to know how to remove the error being generated while running the program. To remove the error, you must define the functions before calling the function. The error is being generated as you are not passing “name1” and “name2” parameters to the “Playerpoint” function. Also, you don’t need to pass “point1 and point 2” as parameters in the “Playerpoint” function as they are being defined inside the function. The following code snippet may help.
%Code Section
n1 = input('Please enter the first user name: ','s'); % let players enter the names
n2 = input('Please enter the second user name: ','s');
[name1,name2] = Playername(n1,n2);
[p1,p2,Name1,Name2]= Playerpoint(name1,name2);
function [p1,p2,Name1,Name2]= Playerpoint(name1,name2)
point1 = 10; % get the points
point2 = 15;
p1 = point1+10;
p2= point2 +10;
Name1 = name1;
Name2 = name2;
fprintf("The first %s user has %d points.\n",Name1,p1);
fprintf("The second %s user has %d points.\n",Name2,p2);
end
function [name1,name2] = Playername(n1,n2)
name1 = n1;
name2 = n2;
end
Please refer to the following documentation for more information.
I hope it helps!
Thanks.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!