Problems in compiling code due to the modulus operator
std::pow
in its various guises returns a floating point type, even if the arguments are integral types.
Since %
requires integral arguments, compilation will fail.
Using (long)(pow(10,i))
is one fix, checking of course that (long)
is long enough. Note though that even under IEEE754 pow
is not required to return the best floating point value possible, so the truncation to long
can occasionally be harmful; perhaps std::round
followed by the cast to long
is to be preferred. Although the current fashion is to consider any implementation of pow
that breaks for integral arguments to be defective.
In your case though I'd be tempted to define
constexpr/*use const on earlier standards*/ int powers[] = {1, 10, 100, 1000};
and index appropriately.
You can only use %
with integers, and pow
produces floating-point numbers.
You could write an integer power function, or use a predefined table, but it's simpler to reverse the order of construction and start with the rightmost digit:
int main()
{
int arrx[4]; //stores the individual digits of number as array
int digx = 4; //total number of digits in number
long int dupx = 1234; //number which has to be stored in array
for(int i = 0; i < digx; i++)
{
arrx[digx-i-1] = dupx%10;
dupx = dupx/10;
}
return 0;
}