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

Viewed 81

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);
3 Answers

Take the input as thousands: enter the numbers as 3005 and 3700, and in the end divide the result by 1000.0.

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

To allow flexibility in the number digits and not require them to be the same, when reading, note the offsets with "%n".

int o1, o2
printf("first number:");
// scanf("%d.%d",&n1.integer,&n1.fraction);
scanf("%d.%n%d%n",&n1.integer,&o1, &n1.fraction, &o2);
int n1digit = o2 - o1;

Same for n2 denominator

Apply the sign of the integer part to the fraction part. OP's code does not do this.

When adding the fractions, form a common power of ten, then add the fractions.

Note: This approach fails with pathological inputs like "-1. 23", "1.-23", "12.", etc.

Related