How to divide float by integer when both are variables?

两盒软妹~` 提交于 2020-01-23 13:07:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!