Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Long not giving the result I expect it to

I am using the below code to get a long int sum of 2 numbers.
I take the inputs as long ints and expecting a long int answer through printf but am getting the result as a negative number.

#include <stdio.h>

int main(void)
{
    long x;
    long y;      
    printf("enter x:\n");
    scanf("%ld", &x);
    printf("enter y:\n");
    scanf("%ld", &y);
    printf("%li\n", x + y);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I make one small change to your code, I get your output:

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    int32_t x;
    int32_t y;      
    printf("enter x:\n");
    scanf("%d", &x);
    printf("enter y:\n");
    scanf("%d", &y);
    printf("%i\n", x + y);
}
% ./a.out
enter x:
2000000000    
enter y:
2000000000
-294967296

This indicates that you’re using a platform where long is 32-bits. To ensure you’re using a 64-bit signed int, use int64_t rather than long.

You should also get in the habit of checking the return value from scanf so that you can know when I/O has failed and address it immediately.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading