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)