Ryad Kovach Ryad Kovach - 11 months ago 122
C Question

C - Print int variable in float

after looking for all answers I still coudnt find solution for my code.

Variables needs to be type INT, but in one case I need to print decimal solution. I have tried with casting, still didint work.


int main()
int sum = 6;
int product = 24;
int differenz, result, division, rest, decimal;

differenz = ++product - sum++;
result = differenz * sum;
division = result / 9;
rest = result % 9;
decimal = result / 9.0;

printf("Result = %d\n", result);
printf("Integer division = %d\n", division);
printf("Remainder = %d\n", rest);
printf("Division = %.2f\n", (float) decimal);

return 0;


Result = 133

Integer division = 14

Remainder = 7

Division = 14.00 <-- Here I am supposed to print 14.76

I have also tried:

float b = (float) decimal;
printf("Division = %.2f\n", b);

Still Division = 14.00

Any tip will be appreciated.
Thanks in advance!

Answer Source

This is because you created the variable decimal as an int and you're trying to print it as a float.

Either create the variable as a float, or print it as an int, but you cannot mix both.

Also, casting an int to a float will just add the ".00", you won't be able to modify that.