Thread: Adding two numbers

  1. #1
    Maybe
    Guest

    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

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >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
    My best code is written with the delete key.

  3. #3
    booyakasha
    Join Date
    Nov 2002
    Posts
    208
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about random numbers
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 07-02-2008, 06:28 AM
  2. Adding up all the numbers in the list...
    By Grayson_Peddie in forum C# Programming
    Replies: 0
    Last Post: 06-04-2003, 11:57 AM
  3. adding base n numbers
    By doogle in forum C++ Programming
    Replies: 4
    Last Post: 11-11-2002, 11:23 AM
  4. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM
  5. adding odd numbers
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 09-06-2001, 01:44 PM