#include<iostream>
using namespace std;
int main ()
{
double avr_apple;
int total_apple, category;
total_apple=13;
category=2;
avr_apple=total_apple/category;
cout<<"average apple is : "<<avr_apple<<endl;
return 0;
}

- 18,008
- 2
- 24
- 52
-
1Dividing two integers results in an integer (losing the fraction). Only then is the result assigned to a double – Michael Veksler Jul 20 '20 at 08:07
-
1Since both `total_apple` and `category` are integers, `total_apple/category` is an *integer* division, with an integer result. Assigning that integer result to a floating point variable can't add decimals that aren't there in the integer result. – Some programmer dude Jul 20 '20 at 08:07
-
1Both your variables are integers so you are doing integer division. The result of integer division is always another integer. You should convert one or both of the variable to a double before you do the division. Using a cast is the way to do that e.g. `avr_apple=static_cast
(total_apple)/category;` – john Jul 20 '20 at 08:08
1 Answers
An int
can't hold decimal points. In this line:
total_apple/category;
both total_apple
and category
are int
so when you divide them, you get an int
as a result which doesn't have any decimal points.
To fix this, make total_apple
variable a double or static_cast
it to double:
avr_apple = static_cast<double>(total_apple) / category;
You can also write:
avr_apple = (double) total_apple / category;
Which is the same thing and looks simpler, but is more confusing to me because now I am a bit confused about what is being cast to double, total_apple
?, category
?, the whole result? Hmm. I am also confused about which type of cast is being applied here, is it a static_cast
, is it some other type of cast? So just avoid this.
This also contains a very important lesson, 'A computer only does what it is told to do, nothing more, so make sure you tell it the right thing to do if you want the right result.'

- 8,558
- 4
- 35
- 43