Write a menu‐driven program to investigate the constant π

12 visualizzazioni (ultimi 30 giorni)
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".)

Risposte (1)

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

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by