Write a menu‐driven program to investigate the constant π

3 次查看(过去 30 天)
function choice = pioptions
choice = menu('Choose a pi option','Machin''s formula',...
'Leibniz''s formula: n-terms',...
'Leibniz''s formula: good approx','Exit Program');
while choice==0
disp('Error! Pleace choose')
choice = menu('Choose a pi option','Machin''s formula',...
'Leibniz''s formula: n-terms',...
'Leibniz''s formula: good approx','Exit Program');
end
end
%machin.m
function machin
pie=4 * ( 4 * atan(1/5) - atan(1/239) );
fprintf('pi using Machin''s formula is %.3f\n',pie)
end
%askn.m
function n=askn
n=input('enter a positive value of n:');
while numb ~= int32(n) || n <= 0
n = input('Error! Enter positive integer n:');
end
end
%leibniz.m
function leibniz
n = askn;
num = -4 * cumprod(-ones(1,n));
denom = 1:2:2 * n;
pie = sum(num./denom);
fprintf('Leibniz''s approximation for pi with %d terms is %.4f\n',n,pie);
end
%leibnizgood.m
function leibnizgood
err = 0.01;
N = 1;
S = 2;
runsum = 0;
difference = 1;
while err < difference
term = (-1)^S * 4/N;
temp = runsum;
runsum = runsum + term;
difference = abs(temp - runsum);
N = N + 2;
S = S + 1;
end
fprintf('Using Leibniz''s series, an approximation of pi within %.2f is %.2f\n',err,runsum)
end
choice = -1;
while choice ~=4
choice=pioptions;
switch choice
case 1
machin
case 2
Leibniz
case 3
Leibnizgood
end
end
command window
Error: File: SalmaPantaleonHW6.m Line: 62 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "leibnizgood".)
Error: File: SalmaPantaleonHW6.m Line: 62 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "leibnizgood".)

回答(1 个)

Walter Roberson
Walter Roberson 2019-2-22
When you mix function and script in the same file then the script must be first .

类别

Help CenterFile Exchange 中查找有关 Graph and Network Algorithms 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by