0

I made this program to print up time in hours,minutes and seconds

#include<stdio.h> int main() { float a, b,x,mina,minb,hrsa,hrsb; float seca,secb; FILE *fp = fopen("/proc/uptime", "r"); fscanf(fp, "%f %f", &a, &b); seca=(a)%60; mina=seca/60; hrsa=mina/60; secb=(b)%60; minb=secb/60; hrsb=minb/60; printf("Uptime=%f hrs %f min %f sec",hrsa,mina,seca); printf("Idealtime =%f hrs %f min %f sec",hrsb,minb,secb); return 0; } 

here i am getting an error "invalid operands to binary" in lines 12 and 16.

4 Answers 4

2

You can't do mod (%) on floats. Try ((long)a)%60; Or even (long long), but the 68 years that 1<<31 seconds provides should be sufficient....

Also, you need another mod operation on minutes, or else 3601 seconds becomes "1 hour 60 minutes, 1 second", instead of "1 hour 0 minutes, 1 second".

Sign up to request clarification or add additional context in comments.

5 Comments

I don't see any appearant bonus from using long long, care to explain? (I know about rounding and x86 representation of floats, but in this case it just does not make sense to me).
I was just thinking about the fact that FLOAT_MAX is 1E38 while LONG_MAX is 4E9. I didn't do the math to realize that 4e9 seconds is 136 years, and therefore long should be sufficient.
What you can do, though, is call fmodf or (in C99) remainderf, which will return the floating point remainder
((long)a)) did worked.I have never used this in C.Can you please explain how this work?
It is a typecast. It essentially forces the complier to convert a into a long before the operation. You could think of it as doing long temp = a; seca = temp%60;
2

You can't take a modulus of a float (What is the remainder of 5.5/3? Doesn't make sense).

By the way, /proc/uptime returns values which are already in seconds so seca should be

seca=(long)(a); 

Comments

0

a and b are float, they should be int

Comments

0

Unless you have to do this by hand, take a look at standard time functions.

man time.h

To your code (as others noted) you can't really do integer division and integer mod operation on floats (makes no sense whatsoever).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.