資源描述:
《偽代碼經(jīng)典案例》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、求一元二次方程的根設(shè)計(jì)并編寫一個(gè)程序,用來(lái)求解一元二次方程的根。答案:我們將本章開頭介紹的方法進(jìn)行編程。1.陳述問(wèn)題這個(gè)問(wèn)題的陳述非常的簡(jiǎn)單,我們要求一元二次方程的根,不管它的根是實(shí)根還是復(fù)根,有一個(gè)根還是兩個(gè)根。2.定義輸入和輸出本程序的輸入應(yīng)為系數(shù)a,b,cax2+bx+c=0(3.1)輸出量應(yīng)為兩個(gè)不相等的實(shí)數(shù)。兩個(gè)相等的實(shí)數(shù)或兩個(gè)復(fù)數(shù)。3.寫出算法本程序可分為三大塊,它的函數(shù)分別為輸入,運(yùn)算過(guò)程和輸出。我們把每一個(gè)大塊分解成更小的,更細(xì)微的工作。根據(jù)判別式的值,可能有三種計(jì)算途徑。讀取輸入的數(shù)
2、據(jù)計(jì)算出根輸入出根所以我們要用到有三種選項(xiàng)的if結(jié)構(gòu)。產(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.把算法轉(zhuǎn)化為MATLAB語(yǔ)言%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