-
Is this code good?
I'm really new to C and was wondering if you guys could help me find maybe a better or more efficent way of writing the code i just made, it's a program that'll take input from the user in the format of 8934 seconds and convert it to 2 Hours 45 minutes and 23 seconds.....i think i'm using the wrong variable type for local variable that holds 86400, cause i believe it only goes up to 32000 though, but i can't get it to work when i try long int;
Code:
#include <stdio.h>
int main()
{
int x,d,f,a;
int c;
printf("This here is a program to transfer seconds into Hours Minutes Second format-\n");
printf("Seconds: ");
scanf("%d", &c);
if( c <= 60) {
printf("%d Seconds",c);
sleep(10);
}
else if( c >= 60 && c <= 3600) {
x = c/60;
d = c%60;
printf("%d Minutes %d Seconds",x, d);
sleep(1);
}
else if(c >=3600 && c<= 86400) {
x = c/3600;
d = c%3600;
f = d / 60;
a = d % f;
printf("%d Hours %d Minutes %d Seconds",x,f,a);
sleep(4);
}
else {
print("That's more seconds than in a day ");
sleep(4);
}
}
Thankyou alot!
-
try an unsigned int
so:
becomes
Also
Code:
print("That's more seconds than in a day ");
should be
Code:
printf("That's more seconds than in a day ");
Was also wondering about the purpose of the sleep() you put in.
Oh and I'd change
to
-
you have a mistake in your code
Code:
else if(c >=3600 && c<= 86400) {
x = c/3600;
d = c%3600;
f = d / 60;
a = d % f; // this should be a = d % 60;
printf("%d Hours %d Minutes %d Seconds",x,f,a);
sleep(4);
}
also it would be nice if you #define the 60,3600,etc...
-
Code:
#include <stdio.h>
#define HOUR 3600
#define MINUTE 60
#define DAY 86400
int main(void)
{
int h,m,s,r;
long c;
printf("Enter the value in seconds: ");
scanf("%ld", &c);
if(c > DAY)
{
printf("That's more seconds than in a day\n");
return -1;
}
h = c/HOUR;
r = c%HOUR;
m = r/MINUTE;
s = r%MINUTE;
printf("Result: ");
if(h > 0)
printf("%d hour(s) %d minute(s) %d second(s)\n",h, m, s);
else if(m > 0)
printf("%d minute(s) %d second(s)\n",m, s);
else if(s > 0)
printf("%d second(s)\n",s);
else
printf("Illegal input\n");
return 0;
}