Thread: Sum of 2 numbers with 9 digits

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    1

    Sum of 2 numbers with 9 digits

    Hi! I'm fairly new to C. I wrote a simple c program, a calculator. But when I tried to add 123456789+123456789 it prints the answer as 246913584. I'm not sure what went wrong. Could someone help me?

    Written in Notepad++ compiled in gcc

    Code:
    #include<stdio.h>
    main()
    {
    float n1,n2,sum,sub,div,prod;
    char sym,choice;
    system("cls");
    printf("This is a calculator:\n");
    printf("\nEnter the expression:\n\n");
    cal:
    	scanf("%f%c%f",&n1,&sym,&n2);
    	sum=n1+n2;
    	sub=n1-n2;
    	prod=n1*n2;
    	div=n1/n2;
    	if(sym=='+')
    		{
    		printf("\nSum = %.2f\n\n",sum);
    		goto cal;
    		}
    	if(sym=='-')
    		{
    		printf("\nDifference = %.2f\n\n",sub);
    		goto cal;
    		}
    	if(sym=='*')
    		{
    		printf("\nProduct = %.2f\n\n",prod);
    		goto cal;
    		}
    	if(sym=='/')
    		{
    		printf("\nQuotient = %.2f\n\n",div);
    		goto cal;
    		}
    	if(sym=='?')
    		{
    		getch();
    		}
    }
    https://www.dropbox.com/s/z38tq1ylbz7qlpd/calc.png

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    you are using the type 'float' which has only 24 bits of precision. the numbers you are entering need more than that, so they get approximated which results in the inaccuracy. try your program using 'double' instead of 'float'.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If you are adding or subtracting integers, you should use an integral data type, instead of a floating point type. Also, you should check your MAX_INT in limits.h, and limit input to something that is within the range of the data type you're using. See what you have for extended range integers, also. You should have both signed and unsigned long long int's that will considerably extend the range for the int's.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c++ program-the number of common digits of 2 numbers a & b
    By Sky_Daughter in forum C++ Programming
    Replies: 3
    Last Post: 12-22-2011, 05:03 PM
  2. Dividing numbers with up to 100 digits
    By Dusko in forum C++ Programming
    Replies: 3
    Last Post: 11-26-2011, 01:42 PM
  3. Counting Digits & Numbers
    By yacek in forum C Programming
    Replies: 4
    Last Post: 10-06-2010, 08:44 PM
  4. Comparing numbers to a list of numbers held in a text file
    By jmajeremy in forum C++ Programming
    Replies: 3
    Last Post: 11-06-2006, 07:56 AM
  5. Number system base M, print numbers N digits wide...
    By biterman in forum C Programming
    Replies: 12
    Last Post: 11-19-2001, 04:31 AM