1 ///////////////////////////////////////////////////////////
2 // Softwarebauelemente I, Aufgabe M1.2
3 //
4 // author: Stephan Brumme
5 // last changes: October 14, 2000
6
7
8 // include I/O-streams
9 #include <iostream.h>
10
11
12 // read all coefficients
13 int Read(double **arCoefficients)
14 {
15 // store max. exponent
16 int nMaxExponent;
17
18 // get max. exponent
19 cout<<"Hoechste Potenz: ";
20 cin>>nMaxExponent;
21
22 // allocate some memory on the heap
23 *arCoefficients = new double[nMaxExponent+1];
24
25 // read all coefficients
26 for (int nLoop=nMaxExponent; nLoop>=0; nLoop--)
27 {
28 cout<<"a"<<nLoop<<": ";
29 cin>>(*arCoefficients)[nLoop];
30 }
31
32 // return max. exponent
33 return nMaxExponent;
34 }
35
36
37 // calculate correspending Y-value for a given X using Horner formula
38 double Horner(double dX, int nMaxExponent, double *arCoefficients)
39 {
40 // result, initialize it
41 double dResult = 0.0;
42
43 // go thru the whole array and perform Horner
44 for (int nLoop = nMaxExponent; nLoop>=0; nLoop--)
45 {
46 // dResult_new = dResult_old * dX
47 dResult *= dX;
48 // dResult_new = dResult_old * dX + arCoefficients[nLoop]
49 dResult += arCoefficients[nLoop];
50 }
51
52 // return result
53 return dResult;
54 }
55
56
57 // main function
58 void main()
59 {
60 // store coefficients
61 double *arCoefficients;
62 // get max exponent
63 int nMaxExponent = Read(&arCoefficients);
64 // the X value
65 double dX;
66
67 // get X
68 cout<<"An welcher Stelle soll der Funktionswert berechnet werden: ";
69 cin>>dX;
70
71 // calculate and print Y (using Horner)
72 cout<<"f("<<dX<<") = "<<Horner(dX, nMaxExponent, arCoefficients)<<".\n\n";
73 }
74