diff options
| author | Fuwn <[email protected]> | 2024-04-07 23:18:32 -0700 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2024-04-07 23:18:32 -0700 |
| commit | c1b6ffe70bd281c6c230fd63fabcaac2aff47514 (patch) | |
| tree | e8af3b1782a7cd0754590ed618fddc1bdb9b7385 /chapter9/powers.cxx | |
| download | dscode-main.tar.xz dscode-main.zip | |
Diffstat (limited to 'chapter9/powers.cxx')
| -rw-r--r-- | chapter9/powers.cxx | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/chapter9/powers.cxx b/chapter9/powers.cxx new file mode 100644 index 0000000..3120f3e --- /dev/null +++ b/chapter9/powers.cxx @@ -0,0 +1,59 @@ +// FILE: powers.cxx
+// A demonstration program for two recursive functions that compute powers.
+#include <cassert> // Provides assert
+#include <cstdlib> // Provides EXIT_SUCCESS
+#include <iostream> // Provides cin, cout
+using namespace std;
+
+double power(double x, int n);
+double pow(double x, int n);
+
+int main( )
+{
+ double x;
+ int n;
+
+ cout << "Please type a value for x (double) and n (int) : ";
+ cin >> x >> n;
+ cout << "The value of x to the n is: " << power(x, n) << endl;
+
+ cout << "Please type a value for x (double) and n (int) : ";
+ cin >> x >> n;
+ cout << "The value of x to the n is: " << power(x, n) << endl;
+
+ return EXIT_SUCCESS;
+}
+
+double power(double x, int n)
+{
+ double product; // The product of x with itself n times
+ int count;
+
+ if (x == 0)
+ assert(n > 0);
+
+ if (n >= 0)
+ {
+ product = 1;
+ for (count = 1; count <= n; count++)
+ product = product * x;
+ return product;
+ }
+ else
+ return 1/power(x, -n);
+}
+
+double pow(double x, int n)
+{
+ if (x == 0)
+ {
+ assert(n > 0);
+ return 0;
+ }
+ else if (n == 0)
+ return 1;
+ else if (n > 0)
+ return x * pow(x, n-1);
+ else // x is nonzero, and n is negative
+ return 1/pow(x, -n);
+}
|