You mentioned in a comment that the input has to be a number.
This first point to mention is that when coding, we are not manipulating such abstract things as numbers,
but imperfection representations of numbers. Think to the famous painting "This is not a pipe".
Same here, "This is not a number".
float
, double
and char*
are all or can be all representations of numbers.
Depending on the context, one representation can be more suitable than others. Here, using a char*
is the best solution, has no internal conversion error occurs.
Now, let us assume that the input format double
is imposed by your professor.
Why is your code not working? Mainly because internally, the representation of the numbers is generally imperfect.
A small error can lead to a large error when converting a float to an integer.
For example, int i = 0.999999
will give i = 0
.
The solution is to account for the internal error representation, by introducing a margin, e.g. eps = 1.0e-14
,
when performing the float-to-integer conversion, or when testing if a number is equal to 0.
A difficulty is that the internal error is multiplied by 10 when the number is multiplied by 10. So the value of eps
has to be updated accordingly.
Moreover, we have to take into accout that the mantissa provides a relative accurracy only, not an absolute one.
Therefore, the eps
value must be increased when the number is large.
0.123456789 --> 45
19.1 -> 1
12.45e-36 -> 12
12345.973 -> 19
0.83 -> 11
#include <stdio.h>
int main() {
double num, numfloat;
int digitf, numint, sumf = 0;
double eps = 1.0e-14; // to deal with representation inaccuracy of numbers
if (scanf("%lf", &num) != 1) return 1;
printf("number in memory: %.20g\n", num);
if (num < 0.0) num = -num;
numint = (int) (num + eps);
numfloat = num - numint;
int deal_with_low_number = numint == 0;
while (numint) { // the mantissa only proposes a relative accurracy ...
eps *= 10;
numint /= 10;
}
while (numfloat > eps || deal_with_low_number) {
numfloat *= 10;
digitf = (int) (numfloat + eps);
numfloat -= digitf;
sumf = sumf + digitf;
if (digitf != 0) deal_with_low_number = 0;
if (!deal_with_low_number) eps *= 10;
}
printf("Sum float %d\n", sumf);
return 0;
}