mintbox
mintbox

Reputation: 167

C++ Separating an Integer

int quotient(int , int );
int remainder(int , int );
void seperate(int);    

int main()
{
    int input;

    cout << "Input int " << endl;
    cin >> input;

    seperate(input);
}


int quotient(int divident, int divisor)
{
    return divident / divisor;
}

int remainder(int divident, int divisor)
{
    return divident % divisor;
}

void seperate(int input)
{

    int integers[6] = {};

    for (int i = 1; i <= 5; i++)
    {
        integers[i] = quotient(remainder(input, pow(10, 6 - i)), pow(10,5 - i));
    }

    for (int i = 1; i <= 5; i++)
    {
        cout << integers[i] << setw(2);
    }

    cout << endl;

}

I am wondering why integer separation works for integers with small value (ex 1234) but doesn't work with big values (ex 32767) . Outcome for such big input values come as 3 2-2-3-3 (with dashes). Any suggestions?

Upvotes: 0

Views: 103

Answers (4)

mazhar islam
mazhar islam

Reputation: 5619

double pow (double base, double exponent);

pow() returns double but in the called function you received the value as int.

Try to downcast it like this:

integers[i] = quotient(remainder(input, (int)pow(10, 6 - i)),
                                         ^^^  
                (int)pow(10, 5 - i));
                 ^^^

Explanation: math.h also has a function named remainder,

extern double remainder _PARAMS((double, double));

So, when you call you remainder(int&, double) it is ambiguous for compiler to detect which remainder() will compiler execute.

Upvotes: 3

user1084944
user1084944

Reputation:

Floating-point calculations generally are not exact. When you call, for example, pow(10, 3), you want a result that is exactly 1000, not something that is within floating-point tolerance of 1000.

When the numbers become sufficiently large, those errors have an effect. And since you're using discontinuous functions, they can have a very large effect.

What you need to do is to avoid floating-point arithmetic entirely: don't use pow to compute these quantities. Find another way to do this, such as writing your own integer exponentiation function.

Upvotes: 0

Shreevardhan
Shreevardhan

Reputation: 12641

If you don't want to use intermediate values (digits of an integer), you can simplify it a lot. For example

#include <bits/stdc++.h>
using namespace std;

void print(int input) {
    if (input < 1) return;
    print(input / 10);
    cout << input % 10 << setw(2);
}

int main() {
    int input;
    cin >> input;
    print(input);
    return 0;
}

Input

32233

Output

3 2 2 3 3

or using a string to print (C++11)

#include <bits/stdc++.h>
using namespace std;

int main() {
    int input;
    cin >> input;
    for (auto i : to_string(input))
        cout << i << setw(2);
    return 0;
}

Upvotes: 0

MKR Harsha
MKR Harsha

Reputation: 115

Downcast return type of pow to int and change the remainder function name as remainder is predefined function.

Upvotes: 0

Related Questions