-
Math woes(please help)
I need a function that calculates x to the xth power, but that prints out the whole answer. i.e. 12^12=8916100448256. Using pow() only allows for so many digits to be shown, and then it kicks in using scientific notation. Hopefully, there is a way to get every digit in the answer to be output.
Any insights?
-
exponential calculation
You can store the values into an array to prevent overflow. Which requires some fun logic. but for shorter versions this should do (+ or - the off by one margin)
cin >> nBase; //lets say nBase is 10
cin >> nPower; //lets say nPower is 3 .... 10 ^ 3 = 1000
nResult = 1;
for(i =1;i<=nPower;i++)
{
nResult *= nBase;//1st loop nResult = 1 * 10
//2nd loop nResult = 10 * 10
//3rd loop nResult = 100 * 10
}
if(nPower == 0)
nResult = 1; //any number to the 0 power is 1
cout << nResult;
this is only pseudo code ... I have not executed this code but with a few fixes the logic will work
-
just use pow() from math.h or cmath. Its there provided for you.... why write another???
-
You can either use a 'double' or else a 'float' with pow(). Use the double if you want more decimal places. It this is not enough than you need to get an I64 microprocessor, WinXP professional for 64-bit computers, and an appropriate motherboard. The I64 technology will allow you to work with much larger built in types.
-
If you've got MSVC then you can use __int64 to obtain more precision. As it's non-standard you'll have to write your own functions to work with it and I had to convert all values to a char before I could print them accurately -
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
unsigned __int64 i=12;
char f[64];
int power = 12;
for (int j=1;j<power;j++)
{
i*=power;
}
cout << _i64toa(i,f,10)<<endl;
return 0;
}
other compilers may offer their own 64 bit int.
-
Borland C++ (and C++Builder) also have __int64's (if that is the compiler you use). Also, I would recommend using unsigned __int64's to get a little more precision.
Code:
int main()
{
bool negative = false;
__int64 a;
int b;
unsigned __int64 result;
// Get input for a and b;
if(a < 0 && b % 2 != 0)
negative = true;
result = abs(a); /* I don't think abs() is actually defined for __int64's, but it isn't hard to write one. */
for(int j = 1; j < b; j++) result *= abs(a);
if(negative)
cout << "-";
cout << result;
}
-
> calculates x to the xth power, but that prints out the whole answer. i.e. 12^12=8916100448256
Depends how big your number can get. floats / doubles / int64 will only take you so far (actually floats are worse than int) before you run out of bits to accurately represent the number (and hence accurately print the number), before you have to resort to using something like this