I'm writing a function that's suppose have the float "length" passed to it and then display a timer like output. The float "length" is meant to be in minutes.
When I run it, the output should be: 02:03:27:00. Instead it displays 02:03:26:100, while being technically correct it's A) Not how it should displayed and B) Shows that there's a bug somewhere that may cause undesired results in the future.
After going through it manually with a calculator and finding all the math to be sound. I then commented out the parts that formats the zeros to see if that was causing the bug and the problem was still there. I then went through putting printf's after every calculation and found that while "length" is set to 123.45 it's being stored as 123.449997?
I haven't a clue way it's doing this. And because I don't know way or how this is happening I can't write a reliable fix for it.
int main()
{
float length;
float working;
int hour;
int min;
int sec;
int centi_sec;
char hzero[2];
char mzero[2];
char szero[2];
char czero[2];
length=123.45;
working=floor(length);
working=(length-working)*60;
sec=floor(working);
working-=floor(working);
centi_sec=(working*100)+.5;
working=floor(length);
hour=floor((working/60));
min=working-(hour*60);
if(hour<10){
hzero[0]='0';
hzero[1]="";
}
else if(hour==0){
hzero[0]='0';
hzero[1]='0';
}
else{
hzero[0]="";
hzero[1]="";
}
if(min<10){
mzero[0]='0';
mzero[1]="";
}
else if(min==0){
mzero[0]='0';
mzero[1]='0';
}
else{
mzero[0]="";
mzero[1]="";
}
if(sec<10){
szero[0]='0';
szero[1]="";
}
else if(sec==0){
szero[0]='0';
szero[1]='0';
}
else{
szero[0]="";
szero[1]="";
}
if(centi_sec<10){
czero[0]='0';
czero[1]="";
}
else if(centi_sec==0){
czero[0]='0';
czero[1]='0';
}
else{
czero[0]="";
czero[1]="";
}
printf("%s%d:%s%d:%s%d:%s%d\n", hzero, hour, mzero, min, szero, sec, czero, centi_sec);
system("pause");
}
I've also written a short program just to cheek that the problem wasn't being influence by something in the full program that I had missed and it's having the same issue.
int main()
{
float length=123.45;
printf("%f\n", length);
system("pause");
}
P.S. When I was using printf to troubleshoot the problem, I discovered that the printf's were messing up the formatting of the zeros. Not too big of a issue since when I removed them the formatting went back to how it should be. Still it doesn't make any sense that printf's would be messing up the formatting. If anyone can provide an answer to this too, it would be appreciated.
Thanks in advance.