Search code examples
cfloating-pointint

Is it possible to add 3.005 to 4.70 only using int types in C?


I am asked to input two numbers like 3.005, 3.70 and add, subtract and multiply them without using float or double. Somehow i managed to do something similiar to what i am asked. I input numbers individually. If i input "3.005" i first input 3, then i input .005. But since 005 doesn't equal to 0.005 i'm having problems. For example i input 3.005 and 4.70 and when i add them i get 7.75, which is not true. How can i fix that? That's how i input my values.

printf("first number:");
scanf("%d.%d",&n1.integer,&n1.fraction);
printf("second number:");
scanf("%d.%d",&n2.integer,&n2.fraction);

That's my function for adding two values.

int add(n1,f1,n2,f2,n1digit,n2digit){ //n1-2digit is number of digits of n1-2's fraction.
int t;
int y=1; 
int fraction;
int integer;
if (n1digit>n2digit){
    t=n1digit;

}
else if (n2digit>n1digit){
    t=n2digit;
}
else { 
    t=n2digit;
}
fraction=f1+f2;
integer=n1+n2;

int temp=fraction;
int i=0; 
while (temp>0){
    temp=temp/10;
    i=i+1;
}
if (i>t){
    integer=integer+1; 
    y=pow(10,i-1);
    fraction=fraction%y;


}
printf("%d.%d\n",integer,fraction);

Solution

  • With the hint you have posted to @ruohola's answer, you could do the following:

    1. define a maximum number of fractional digits, e.g. 3 or 6
    2. read the number as a string, use strtol() to convert the integer part. and skip '.'
    3. if the fractional part is shorter then the number of fractional digits, append an according number of '0', so '70' becomes '700' or '700000', '5' becomes '500' or '500000'
    4. use strtoul() to store that number into another (unsigned) integer value

    Now you have yout two integer values representing the number an can do the rest