How to divide 2 int in c?

若如初见. 提交于 2019-11-27 06:20:56

问题


wanna divide 2 numbers and get the result like this:

5 / 2 = 2.50

But it only outputs 2.

I don't now what i'm doing wrong.

Here my code:

int a;
int b;
int c;
printf("First num\n");
scanf("%d", &a);
printf("Second num\n");
scanf("%d", &b);
c = a / b;
printf("%d", c);

回答1:


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.




回答2:


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);



回答3:


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.




回答4:


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.5f

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




回答5:


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.



来源:https://stackoverflow.com/questions/35069863/how-to-divide-2-int-in-c

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