问题
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);
Here I am doing some computations on b so its value is increased randomly i.e 33 etc.
c = b/(float)a;
printf("c = %2.f\n", c);
The problem is I am getting 'c' as a rounded number (integer) rather than a float value. How can I get 'c' as a float value.
回答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.
回答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
回答3:
When printing on a screen try this (this worked for me):
printf("c = %f\n", c);
来源:https://stackoverflow.com/questions/21307390/how-to-divide-float-by-integer-when-both-are-variables