|
From: Per W. <pw...@ia...> - 2006-03-23 17:12:27
|
Since the second parameter is an integer and you want good precision, just
typecast the first parameter to double.
However, the reason that there are no pow(int,int) is that you normally
don't use pow when playing with integers.
just do:
n = num;
count = 0;
while (n >= 10) {
n /= 10;
count++;
}
to find out # of times you can divide by 10.
Normally when extracting digits, it is performed in reverse, i.e.
something like (I might have a +/- 1 error somewhere since I'm just
writing without testing):
char digits[30];
char* p = digits+30;
int negative = n < 0;
if (n < 0) n = -n;
*(--p) = '\0';
*(--p) = '0' + (n % 10);
n /= 10;
while (n) {
*(--p) = '0' + (n % 10);
n /= 10;
}
if (negative) *(--p) = '-';
std::cout << digits << std::endl;
/Per W
On Thu, 23 Mar 2006, Sheets, James D. wrote:
> This is the program I am trying to compile:
> // Programming Exercise 2
> #include <iostream>
> #include <cmath>
> using namespace std;
> int main()
> {
> int num;
> int digit;
> int sum = 0;
> int pwr = 0;
> cout << "Enter an integer: " << flush;
> cin >> num;
> cout << endl;
> cout << "The digits of " << num << " are: ";
> if (num < 0)
> num = -num;
> //Find the highest power of 10 that divides the number
> while (num / static_cast<int>(pow(10, pwr)) > 10)
> pwr++;
>
> while (num > 0)
> {
> digit = num / static_cast<int>(pow(10, pwr));
> cout << digit << " ";
> sum = sum + digit;
> num = num % static_cast<int>(pow(10, pwr));
> pwr--;
> }
> if (pwr != -1) //Either num is 0 or there are trailing zeros in num
> while (pwr != -1)
> {
> cout << 0 << " ";
> pwr--;
> }
> cout << endl;
> cout << "The sum of the digits = " << sum << endl;
> return 0;
> }
>
> I have the following statement giving me an error when compiled;
> while (num / static_cast<int>(pow(10, pwr)) > 10)
>
> The debug has the following:
> Line File Name Message
> 26 C:\Files\Ch5Ex2. cpp call of overloaded `pow(int, int&)' is ambiguous
> note C:\Dev-Cpp\include\math.h:150 candidates are: double pow(double, double)
> note C:\Dev-Cpp\include\math.h:150 long double std::pow(long double, int)
> note C:\Dev-Cpp\include\math.h:150 float std::pow(float, int)
> note C:\Dev-Cpp\include\math.h:150 double std::pow(double, int)
> note C:\Dev-Cpp\include\math.h:150 long double std::pow
|