0

what i coded is

#include <stdio.h>
int main(){

    float a, b;

    printf("enter initial value.");
    fflush(stdout);
    scanf("%f", &a);

    printf("add up the following number.");
    fflush(stdout);
    scanf("%f", &b);


    printf("current value is %f.\n", (a+b));
    fflush(stdout);


    b = a+b;

    printf("enter a value to subtract.");
    fflush(stdout);
    scanf("%f", &a);


    printf("current value is %f. \n", b-a);
    fflush(stdout);

    b = b-a;

    printf("enter a value to multiply.");
    fflush(stdout);
    scanf("%f", &a);



    printf("current value is %f. \n", a*b);
    fflush(stdout);

    b = a*b;

    printf("enter a value to devide.");
    fflush(stdout);
    scanf("%f", &a);



    printf("current value is %f. \n", b/a);
    fflush(stdout);



    return 0;
}

Output:

enter initial value. 1000000
add up the following number. 9000000
current value is 10000000.000000.
enter a value to subtract. 0
current value is 10000000.000000. 
enter a value to multiply. 1000000
current value is 10000000000000.000000. 
enter a value to devide. 10
current value is 999999982796.800050. 

https://i.stack.imgur.com/xuqab.png

i want 1000000000000.000000 as a result but 999999982796.800050 is all i've got.... what should i fix?

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
Tae L
  • 19
  • 4

2 Answers2

0

Single precision float can represent any real number for 6 decimal digits of precision. 999999982796.800050 meets that criteria.

This specific example may be fixed simply by using double, which is good for 15 decimal digits of precision.

Clifford
  • 88,407
  • 13
  • 85
  • 165
0

If you must handle math with arbitrary precision for very large numbers, instead of using a float or double, look into an arbitrary precision library. A common on is called GMP

The idea behind an arbitrary precision library is the same as the idea behind how we do math as humans. A single "digit" can only store 10 possible values, but by creating an array of digits we can generate indiscriminately large values without losing accuracy.

Libraries like this utilize arrays and perform math one digit at a time in order to maintain perfect accuracy. They run a lot slower than floats or doubles, but if you care more about precision than speed then it's definitely the way to go.

stevendesu
  • 15,753
  • 22
  • 105
  • 182