I am trying to get the amount of decimals a number has in c: 0.0001 -> 4 decimals, 3,54235 -> 5 decimals, and so on (If you don't get it, the number of numbers behind the comma.) our teacher sais it can be done in two ways, using a string and not using a string. I figured i would go ahead not using a string because I have NO experiance with strings.
So this is what I came up with
int funzione1(float decimals){
int x=1,c=0,y=1;
while (x!=0){
if((decimals - y) > 0){
y = y / 10;
c++;
}else{
decimals = decimals - y;
}
if(decimals == 0)
x=0;
}
return c-1;
}
When calling the function it should return the amount of decimals I figured, but it does not, actually it gets stuck in an infinite loop.
the Idea behind this code was to for every number in the "string" of numbers to get them to 0 and then check if the total number was 0
3.456 c=0
0.456 c=1
0.056 c=2
0.006 c=3
0.000 return c
But That leaves me with two problems 1 how to detirmine tha amount of numbers before the comma for like 5564.34234 this code will not work because it will count to 8 before the full number is a solid 0. and therefor not return the right number of decimals.2. the code I designed isn't working. Just gets stuck in an infinite loop. I don't know where the infiniteness of the loop is created.
How do i get this code to work?
PS. I found this article about this problem in Java: How to find out how many decimals a number has? but it is using strings and I would not like that because of the fact that I don't know how to use strings.
edit: Here is another piece of code i tried and which faild really bad givving an output of 50 when you enter a number higher than 1 and 0 if the number is lower than 0(I don't get it, not a little bit) anyway here is the code:
int funzione1(float decimals){
int i=0;
while(decimals!=((int)decimals)){
i++;
decimals=decimals*10;
}
return i;
}