pikafan_8080
pikafan_8080

Reputation: 379

Problems in compiling code due to the modulus operator

I have written a program to store a number (which is predefined by the programmer) in form of digits in an array.

For example, if I want to store a number 1234 in array arrx[4], then its elements would be:

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4

I try to achieve this using the below piece of code:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int arrx[4];    // Stores the individual digits of number as array
    int digx = 4;   // Total number of digits in number
    int i;
    long int dupx = 1234;  // Number which has to be stored in array
    for(i = digx-1; i >= 0 ; i--)
    {
        arrx[digx-i-1] = int(dupx/pow(10,i));
        dupx = dupx%(pow(10, i));
    }
    return 0;
}

However, when I try to compile the above code, I get the following error message:

error: invalid operands of types 'long int' and 'double' to binary 'operator%'

The only conclusion which I was able to draw from above error was that the problem is with the modulus operator.

Therefore, I have following questions in my mind

  1. What exactly is the problem with the code containing modulus operator?

  2. How can I fix this?

I am using Code::Blocks version 17.12 with GNU GCC as my compiler.

Upvotes: 10

Views: 1332

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

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;
}

Upvotes: 15

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 13

Related Questions