-
Adding two numbers
What's wrong with this?
Code:
#include <stdio.h>
int main (void)
{
printf("Enter a number\n");
int x=getchar();
while(getchar() != '\n');
printf("Enter a number\n");
int y=getchar();
int result=y+x;
printf("Here is the result %d\n", result);
return 0;
}
It doesn't add the numbers successfully
-
>What's wrong with this?
First, you try to declare variables in locations other than the beginning of the block. This is illegal unless you use C99 or C++, the latter is just silly. Second, the addition works perfectly, just not the way you expected. By using getchar, you assign the value of the character to an int, not the value that the character represents. Perhaps something more like this was what you were expecting (error checking omitted):
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int x;
int y;
int result;
printf("Enter a number\n");
scanf("%d", &x);
while(getchar() != '\n');
printf("Enter a number\n");
scanf("%d", &y);
result=y+x;
printf("Here is the result %d\n", result);
return 0;
}
-Prelude
-
you are reading the first char into x and y,
instead of reading the number in.
keep in mind
char c = '2';
int x = 2;
(int)c is not equal to x
if you use c as a number it will be the ASCII value of '2' not the number 2