How to divide float by integer when both are variables?
Solution 1
Your problem is here:
printf("c = %d\n", c);
%d
formats c as integer. Use %f
instead.
Or std::cout << "c = " << c << std::endl
if you prefer.
Solution 2
For those here coming from a Google search because of the question's name:
The result of dividing a float by an integer is a float, this is clean and safe. Example:
#include <iostream>
int main()
{
float y = 5.0f;
int x = 4;
std::cout << y/x << std::endl;
}
The output is as expected: 1.25
Solution 3
When printing on a screen try this (this worked for me):
printf("c = %f\n", c);
user3130920
Updated on June 02, 2020Comments
-
user3130920 almost 4 years
I am writing a program in C. I have two variables one of which is integer and the other one is float. I want to divide the float by the integer and want to get result in float. I am doing the following:
int a; float b=0,c=0; scanf("%d",&a);
I then do some computations on
b
so it has a non-zero value.c = b/(float)a; printf("c = %d\n", c);
The problem is I am getting
c
printed as a rounded number (integer) rather than a float value.How can I get
c
as a float value?