I am calculating salary by inflation By random 1 to 5% the salary increase. For exam, in 2020 inflation increased by 2%. And my salary is 1000. Then answer should be 1000 * 1.02 = 1020.
So I made a simple code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned int)time(NULL));
int inc_rate = (rand() % 5) + 1;
float num = (100 + inc_rate) / 100;
printf("%d \n", inc_rate);
printf("%f", 100 * (float)num);
return 0;
}
But if I run it cannot count 1.02.
For example the outcomes
2
100.000000
How can I calculate division by C
The operator "/" performs integer division if both operands are integers (the fractional part is discarded). This means that the expression
(100 + inc_rate) / 100
will always be one if inc_rate is an integer between one and five.
Try this instead:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int inc_rate = (rand() % 5) + 1;
float num = (100.0 + inc_rate) / 100.0;
printf("%d\n", inc_rate);
printf("%f\n", 100.0 * num);
return 0;
}