Search code examples
ccasting

Typecasting in division in C


#include <stdio.h>
int main(void) {
    int t;
    long long int a[100000], n, i;
    scanf("%d\n", &t);
    while(t){
        t--;
        scanf("%d", &n);
        printf("%ld\n", n);
        n = n * (n-1);
        printf("%ld\n", n);
        n = n/2;
        printf("%ld\n", n);
    }
    return 0;
}

Can't figure out the problem in division. It's returning garbage value in the third printf statement. Can you please help me identify where the problem is?


Solution

  • The format specifier for long long int is lld, not ld.

    That's especially important in the scanf as using the wrong specifier may end up putting the data in the wrong bytes within the variable.