Why am I losing the rest of the value after doing arithmetic in C?
I'm trying to learn basic C programming by following a tutorial and I must be missing something about data types, rounding, and / or order of operations, because when I try to create a simple program to convert seconds to hours and minutes, the clock runs, but the remaining minutes go out to 0 when they shouldn't be.
Thanks to Coursera , I know there are huge security vulnerabilities in such programs, but for educational purposes, I ask you to ignore security. For now, the books want me to stick with loops printf
, scanf
and while
as they correspond to the chapters of the tutorial I'm reading (the books let me know what I'll get to start worrying about security as I go a few more chapters further).
My C program looks like this:
/* Ask the user for a number of seconds, convert to X hours and Y minutes */
/* Continue doing this with a while loop until user enters 0 */
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void)
{
const int minperhour = 60;
const int secpermin = 60;
int sec, hr;
float min;
sec = 1;
while(sec != 0)
{
printf("Enter the number of seconds to convert: \n");
scanf("%i", &sec);
min = sec/secpermin;
hr = min/minperhour;
min = (sec/secpermin) - (hr * minperhour);
printf("%d hours and %f minutes \n", hr, min);
}
return 0;
}
I would expect that I can enter 3601
and the result is:
1 hours and 0.01667 minutes
since this expression evaluates in the R language that I'm more familiar with:
> min = 3601/60
> min
[1] 60.02
> hr = min/60
> hr
[1] 1
> min = (3601/60) - (1 * 60)
> min
[1] 0.01667
However, what I get in C is this:
C:\Users\hackr>pa2q3.exe
Enter the number of seconds to convert:
3601
1 hours and 0.000000 minutes
Enter the number of seconds to convert:
7205
2 hours and 0.000000 minutes
Enter the number of seconds to convert:
0
0 hours and 0.000000 minutes
C:\Users\hackr>
I made a second attempt 7205
just for good measure.
I have a feeling that some of you C gurus on Stack Overflow might use more sophisticated techniques to write a protected version of a program in a more concise manner. It might be educational if you want to mention it, but first of all I need to understand what's going on with this simple program.
source to share
Integer division: The integer value after dividing two ints is stored in floating point format. For example:
float a = 3/5;
here an integer division will occur between 3
and 5
, resulting in 0
. Now if you try to store this variable 0
in a variable float
it will be stored as 0.00
.
min = sec/secpermin;
Should be
min = (float)sec/secpermin;
or
min = sec/(float)secpermin;
or, as @alk pointed out, you can also do this:
min = sec;
min /= secpermin; // min=min/secpermin; here, typecasting is not required as
// numerator (min) is already float.
Alternatively, you can do them all float
, and at print time, output them as int
.
source to share