1

I am fairly new to programming. When I build this program I do not get any errors using visual express. But when I run it without debugging it displays the first cout statement and the answer to the function call number and then crashes. Can anyone tell me what may be wrong?

#include <iostream>
#include <iomanip>
using namespace std;

// This program demonstrates a recursive function.
// The function should accept two arguments, the 
// number to be raised and the exponent. A function 
// template is used to test different data types.
// Assume that the exponent is a nonnegative integer.


template <class T, class TT>
T number(T raised, TT exponent)
{
 if (exponent == 0)
  return 1;
 else 
  return raised * number(raised, exponent -1);
}

void main()
{
// Testing integers
cout << "Testing integers: 5 raised to 2 is "
     << number(5, 2) << endl;

// Testing doubles
cout << "Testing doubles: 5.5 raised to 2.2 is "
     << setprecision(1) << number(5.5, 2.2) << endl;

// Testing floats
cout << "Testing doubles: 5.55 raised to 2.22 is "
     << setprecision(4) << number(5.55f, 2.22f) << endl;

// Testing a double and a integer
cout << "Testing integers: 5.5 raised to 2 is "
     << number(5.5, 2) << endl;
}

EDIT: Thank you for the responses. I understand now. I will adjust if(exponent == 0)

Lilspree
  • 135
  • 2
  • 14

2 Answers2

3

The problem lies in the recursion:

if(exponent == 0) return 1;

What you don't account for is if the number is a double, such as 2.2. After decreasing it by 1 twice it will reach .2 and then -0.8. Never once will it reach 0. This causes a stack overflow as the recursion depth exceeds the stack.

Also void main() is not the right way to define main.

Community
  • 1
  • 1
yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • Thankyou for the quick response. I will change it to `if(exponent < 1) return 1;` I won't get the exact answer but I'll be in range unless there is something I can do to make it work better. – Lilspree Feb 17 '14 at 18:03
  • If my answer answered your question, you could help by accepting it :) – yizzlez Feb 17 '14 at 18:04
0

You broke this assumption:

// Assume that the exponent is a nonnegative integer.

The recursive function works for integer exponents because, eventually, subtracting one from the exponent will give zero, and the function will return.

Passing a non-integer value, such as 2.2, will cause it to recursively call the function with 1.2, 0.2, -0.8, -1.8, and so on until the stack explodes.

In C++11, you could enforce the assumption with, for example,

static_assert(std::is_integral<TT>::value, "Exponent must be an integer");

although you could still have problems if the integer value is too large.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644