Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide 2 int in c?

Tags:

c

division

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);
like image 922
Alex Avatar asked Jan 28 '16 19:01

Alex


4 Answers

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.

like image 135
Haris Avatar answered Oct 05 '22 18:10

Haris


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);
like image 34
LapizLazuli Avatar answered Oct 05 '22 16:10

LapizLazuli


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.

like image 28
Jaffer Wilson Avatar answered Oct 05 '22 16:10

Jaffer Wilson


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.

like image 20
Claudio Cortese Avatar answered Oct 05 '22 18:10

Claudio Cortese