Hi everyones, I do not understand why it does that and i need help. My code end after typing the first number and doesn't go to the second input... thanks in advance.. i'm new to c programming.
my code:
![]()
Hi everyones, I do not understand why it does that and i need help. My code end after typing the first number and doesn't go to the second input... thanks in advance.. i'm new to c programming.
my code:
![]()
Don't post images of code or output. Just post the text. Post code with code tags.
I don't know why it wouldn't be reading two numbers. That doesn't make sense.
Your test for overflow and underflow is wrong for multiple reasons.
The computation a + b converts a and b to ints before the addition ("integer promotions").
Also, it is not guaranteed that signed values will wrap around in that way. It is "implementation defined" and may even raise a signal (I believe gcc has a flag to make it raise SIGABRT).
Also, if you enter a value greater than SHRT_MAX or less than SHRT_MIN in the first place, it's undefined behaviour (all bets are off).
To be safe, you would read the input as a string and then use strtol to convert it to a long and eventually check if it's in the short range.
I won't go into all that, but here's a way to check for overflow/underflow:
Code:#include <stdio.h> #include <limits.h> int main() { short a, b; printf("Enter two numbers between %d and %d, inclusive\n", SHRT_MIN, SHRT_MAX); scanf("%hd%hd", &a, &b); if (a > 0 && b > SHRT_MAX - a) printf("Overflow\n"); else if (a < 0 && b < SHRT_MIN - a) printf("Underflow\n"); else printf("Okay %d\n", a + b); return 0; }
Very kind of you, thanks for the reply!
It doesnt work because after else if you used closed bracketand you need to useCode:}open bracketCode:{
I dont know how did you compile it without error message
and also you used
im also new to c programming but when you useCode:if ((a > 0) && (b > 0) && (a+b<0))evrything inside If () must be trueCode:&&
and if you type for a = 5 and for b = 7
you then havetrue true falseCode:if ((a > 0) && (b > 0) && (a+b<0))
and this is not true it cant become true what ever you type for a and b.
Last edited by kzzmzz; 02-07-2017 at 02:45 AM.
Obviously that's not the code he compiled since, as you say, it won't compile.
You don't know what you're talking about. Obviously the OP was expecting the value to "wrap around" to a negative value if a and b were too large to be added together within a short. I gave the reasons why this is not a good thing to do.you then havetrue true falseCode:if ((a > 0) && (b > 0) && (a+b<0))
and this is not true it cant become true what ever you type for a and b.
Try this yourself:
Although it probably "works" on your machine, it is not guaranteed to work by the C standard. The original question also had problems associated with using short ints.Code:#include <stdio.h> #include <limits.h> int main() { int a = INT_MAX, b = INT_MAX; if (a > 0 && b > 0 && a + b < 0) printf("What do you know?\n"); return 0; }