Home > Mobile >  Why is the output not right even tho im using 'long' data type here?
Why is the output not right even tho im using 'long' data type here?

Time:11-23

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    long x, y;
        
    printf("Enter the first number: \n");
    scanf("%ld", &x);
    
    printf("Enter the second number: \n");
    scanf("%ld", &y);
    
    long z = x   y;
    
    printf("The answer is: %ld \n", z);
    
    return 0;
}

I can't add more than 4 billion here even though i should since im using 'Long' datatype here.

enter image description here

CodePudding user response:

long may hold 32 or 64-bits, depending on the system. It appears your system uses 32-bits. Also, since long is signed, the maximum value long can take is 2**31 - 1 (< 4 billion).

You can instead use

  • unsigned long, which can take values up to 2**32 - 1 (> 4 billion), or
  • long long/unsigned long long, guaranteed to work with at least 64-bits.

You'll also want to change the corresponding format strings to %lu/%lld/%llu.

CodePudding user response:

The allowed range for long may be as small as [-2,147,483,647 ... 2,147,483,647]. This can occur when long is 32-bit.

long may be wider, like 64-bit, and then handle a range of [-9,223,372,036,854,775,807 ... 9,223,372,036,854,775,807].

To certainly handle values like 4 billion, use long long which is at least 64-bit.

long long x, y;
printf("Enter the first number: \n");
scanf("%lld", &x);
printf("Enter the second number: \n");
scanf("%lld", &y);

long long z = x   y;
printf("The answer is: %lld \n", z);

More nuanced code may what to use unsigned long to handle [0 ... 4,294,967,295] or types like int64_t, int_least64_t...

  •  Tags:  
  • c
  • Related