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);
With the hint you have posted to @ruohola's answer, you could do the following:
strtol()
to convert the integer part. and skip '.' strtoul()
to store that number into another (unsigned) integer valueNow you have yout two integer values representing the number an can do the rest