Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I unable to store my data in long data type?

int power(int first,int second) {
    int counter1 = 0;
    long ret = 1;

    while (counter1 != second){
        ret *= first;
        counter1 += 1;
    }
    return ret;
}


int main(int argc,char **argv) {

    long one = atol(argv[1]);
    long two = atol(argv[2]);
    char word[30];
    long finally;

    printf("What is the operation? 'power','factorial' or 'recfactorial'\n");
    scanf("%20s",word);

    if (strcmp("power",word) == 0){
        finally = power(one,two);
        printf("%ld\n",finally);
        return 0;
    } 

}

This function is intended to do the "power of" operation like on the calculator, so if I write: ./a.out 5 3 it will give me 5 to the power of 3 and print out 125

The problem is, in cases where the numbers are like: ./a.out 20 10, 20 to the power of 10, I expect to see the result of: 1.024 x 10^13, but it instead outputs 797966336.

What is the cause of the current output I am getting?

Note: I assume that this has something to do with the atol() and long data types. Are these not big enough to store the information? If not, any idea how to make it run for bigger numbers?

like image 282
Charana Avatar asked Oct 02 '15 10:10

Charana


3 Answers

Sure, your inputs are long, but your power function takes and returns int! Apparently, that's 32-bit on your system … so, on your system, 1.024×1013 is more than int can handle.

Make sure that you pick a type that's big enough for your data, and use it consistently. Even long may not be enough — check your system!

like image 167
Lightness Races in Orbit Avatar answered Nov 16 '22 16:11

Lightness Races in Orbit


First and foremost, you need to change the return type and input parameter types of power() from int to long. Otherwise, on a system where long and int are having different size,

  1. The input arguments may get truncated to int while you're passing long.

  2. The returned value will be casted to int before returning, which can truncate the actual value.

After that, 1.024×1013 (10240000000000) cannot be held by an int or long (if 32 bits). You need to use a data type having more width, like long long.

like image 9
Sourav Ghosh Avatar answered Nov 16 '22 15:11

Sourav Ghosh


one and two are long.

long one = atol(argv[1]);
long two = atol(argv[2]);

You call this function with them

int power(int first, int second);

But your function takes int, there is an implicit conversion here, and return int. So now, your long are int, that cause an undefined behaviour (see comments).

like image 4
MokaT Avatar answered Nov 16 '22 15:11

MokaT