How to divide 2 int in c?

十年热恋 提交于 2019-11-28 11:39:40
Haris

You need a double variable to store the result. int stores only integers. Additionally, you have to typecast the other variables also before performing the division.


Do something like this

double c;
.
.
.
c = (double)a / (double)b;
printf("%f", c);

NOTE:

You do not need the & in printf() statements.

To avoid the typecast in float you can directly use scanf with %f flag.

float a;
float b;
float c;
printf("First number\n");
scanf("%f", &a);
printf("Second number\n");
scanf("%f", &b);
c = a / b;
printf("%f", c);

You have to use float or double variables, not int(integer) ones. Also note that a division between two integers will lead to an integer result, meanwhile a division between a float/double and an integer will lead to a float result. That's because C implicitly promote this integer to float.

For example:

5/2 = 2
5/2.0f = 2.5

Note the .0, this actually means that we are dividing with a float.

The '/' - sign is for division. Whenever in C language, you divide an integer with an integer and store the data in an integer, the answer as output is an integer. For example

int a = 3, b = 2, c = 0;
c = a/b; // That is c = 3/2;
printf("%d", c);

The output received is: 1
The reason is the type of variable you have used, i.e. integer (int)
Whenever an integer is used for storing the output, the result will be stored as integer and not a decimal value.

For storing the decimal results, C language provide float, double, long float and long double.

Whenever you perform an operation and desires an output in decimal, then you can use the above mentioned datatypes for your resultant storage variable. For example

int a = 3, b = 2;
float c = 0.0;
c = (float)a/b; // That is c = 3/2;
printf("%.1f", c);

The output received: 1.5
So, I think this will help you to understand the concept.
Remember: When you are using float then the access specifier is %f. You need to convert your answer into float, just as I did, and then the answer will be reflected.

user9598609

In C, only an int type number is displayed. 5/2 gives a floating point type number. So, the compiler compiles it only with the integer value.

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