資源描述:
《偽代碼經(jīng)典案例》由會員上傳分享,免費在線閱讀,更多相關內容在教育資源-天天文庫。
1、求一元二次方程的根設計并編寫一個程序,用來求解一元二次方程的根。答案:我們將本章開頭介紹的方法進行編程。1.陳述問題這個問題的陳述非常的簡單,我們要求一元二次方程的根,不管它的根是實根還是復根,有一個根還是兩個根。2.定義輸入和輸出本程序的輸入應為系數(shù)a,b,cax2+bx+c=0(3.1)輸出量應為兩個不相等的實數(shù)。兩個相等的實數(shù)或兩個復數(shù)。3.寫出算法本程序可分為三大塊,它的函數(shù)分別為輸入,運算過程和輸出。我們把每一個大塊分解成更小的,更細微的工作。根據(jù)判別式的值,可能有三種計算途徑。讀取輸入的數(shù)
2、據(jù)計算出根輸入出根所以我們要用到有三種選項的if結構。產(chǎn)生的偽代碼如下Prompttheuserforthecoefficientsa,b,andc.Reada,b,andcdiscriminant←b^2-4*a*cifdiscriminat>0x1←(-b+sqrt(discriminant))/(2*a)x1←(-b-sqrt(discriminant))/(2*a)Writemsgthatequationhastwodistinctrealroots.Writeoutthetworoots.e
3、lseifdiscriminant==0x1←-b/(2*a)Writemsgthatequationhastwoidenticalrealroots.Writeouttherepeatedroots.elsereal_part←-b/(2*a)imag_part←sqrt(abs(discriminant))/(2*a)Writemsgthatequationhastwocomplexroots.Writeoutthetworoots.end4.把算法轉化為MATLAB語言%Scriptfile:c
4、alc_roots.m%%Purpose:%Thisprogramsolvesfortherootsofaquadraticequation%oftheforma*x^2+b*x+c=0.Itcalculatestheanswers%regardlessofthetypeofrootsthattheequationpossesses.%%Recordofrevisions:%DateProgrammerDescriptionofchange%==============================
5、===%12/04/98S.J.ChapmanOriginalcode%%Definevariables:%a--Coefficientofx^2termofequation%b--Coefficientofxtermofequation%c--Constanttermofequation%discriminant--Discriminantoftheequation%imag_part--Imagpartofequation(forcomplexroots)%real_part--Realparto
6、fequation(forcomplexroots)%x1--Firstsolutionofequation(forrealroots)%x2--Secondsolutionofequation(forrealroots)%Prompttheuserforthecoefficientsoftheequationdisp('Thisprogramsolvesfortherootsofaquadratic');disp('equationoftheformA*X^2+B*X+C=0.');a=input(
7、'EnterthecoefficientA:');b=input('EnterthecoefficientB:');c=input('EnterthecoefficientC:');%Calculatediscriminantdiscriminant=b^2-4*a*c;%Solvefortheroots,dependingonthevlaueofthediscriminant.ifdiscriminant>0%therearetworealroots,so...x1=(-b+sqrt(discrim
8、inant))/(2*a);x2=(-b-sqrt(discriminant))/(2*a);disp('Thisequationhastworealroots:');fprintf('x1=%f',x1);fprintf('x2=%f',x2);elseifdiscriminant==0%thereisonerepeatedroot,so...x1=(-b)/(2*a);disp('Thisequationhastwoidenticalreal