a regular coder
a regular coder

Reputation: 95

C calculate wrong number in multiplication

i am simply trying to multiply 2 numbers and store them on an unsigned long long variable. however the result seems to be wrong and i also made sure that the result does not cause any overflow to happen. why is it calculating the wrong number?

#include <stdio.h>

int main() {
    unsigned long long num = 0;
    
    num = 260000000 * 25;
    printf("num = %llu\n", num);
    
    num = 0;
    
    for (int i=0; i<25; i++){
        num += 260000000;
    }
    printf("num = %llu\n", num);
    return 0;
}
Result:
num = 18446744071619617024
num = 6500000000

notice in the first example i'm multiplying directly and it produces the wrong number while the second example by looping them manually gives the correct answer.

Upvotes: 1

Views: 72

Answers (1)

user9706
user9706

Reputation:

260000000 * 25 is an int multiplication. If you want an unsigned long long value then you need to use the ULL (or ull) suffix:

    num = 260000000ULL * 25;

Or you write it like this:

    unsigned long long num = 260000000;
    num *= 25;

Or use a cast:

    num = (unsigned long long) 260000000 * 25;

Upvotes: 6

Related Questions