Help - the static_cast< double > is not calculating the value of term and I cannot see what is wrong.

void eConstant::compute()
{ 
   cout << "Enter the desired level of accuracy to calculate the mathematical constant e,   
   \nmeaning the number of terms in the summation: ";

   cin >> accuracy;

   validate(accuracy);
   setAccuracy(accuracy);

	int denominator = 0;
	double term = 0;
	while (accuracy > 0)
	{
		if (accuracy == 1)
		{
			e += 1;
			accuracy -= 1;
		}
		else
		{
			denominator = nFactorial(accuracy - 1);
			term = static_cast< double >((numerator/denominator));
			e += term;
			
			accuracy -= 1;
		}
	}
}

int eConstant::nFactorial(int position)
{
	int value = 0;
	int n = position;
	factorial = 1;
	int factor = 0;

	do
	{		
		factor = n - value;
		factorial *= factor;
		value += 1;
	} while (value < position);

	return factorial;

}

term = static_cast< double >((numerator/denominator));

is evaluating the double after doing int division within the cast. Try--

term = static_cast< double >(numerator)/denominator;

1. 13! overflows an int. So unless you're keeping to really small values, expect trouble here.


2. (numerator/denominator)
If both of these are ints, the result is integer division (truncation towards zero, result is an integer). Cast one of them to double before dividing, not afterwards.

1. 13! overflows an int. So unless you're keeping to really small values, expect trouble here.


2. (numerator/denominator)
If both of these are ints, the result is integer division (truncation towards zero, result is an integer). Cast one of them to double before dividing, not afterwards.

Hi,

Will casting one of them also take care of the larger numbers?

Thank you,

Hi,

Will casting one of them also take care of the larger numbers?

Thank you,

Why not just make your factorial method return a long?

Edit: denominator will also have to be declared a long and not an int, since you're assigning denominator the value returned by the factorial method.

int or long int makes no difference.
13! is 6,227,020,800 which overflows them both.

Make it a double.

Thank you :-D

The long method did work because i calculated it with 13 and it gave me the exact anwer: 2.71828

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.