Write a menu‐driven program to investigate the constant π

조회 수: 12 (최근 30일)
Salma A Pantaleon Damaso
Salma A Pantaleon Damaso 2019년 2월 22일
댓글: Walter Roberson 2020년 2월 12일
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에서 Data Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by