I'm really new to C++, been doing it for only 2 days and while trying to create random things I noticed that I couldn't use cout to print numbers with decimal places.
For example, why does this code print the number 3 instead of 3.5? I've tried searching for the solution but I can't find it, please help.
1 2 3 4 5 6 7 8 9
#include <iostream>
usingnamespace std;
int main()
{
double a = 7/2;
cout << a << endl; // prints out the number 3 instead of 3.5
}
Just to give a little clarity as to why (Not full clarity) this happened. When you did double a = 7/2, you gave it two integers which told the computer to use integer division which would return an integer versus the version that would return a double. To do this we could do something called type casting. In this case we would be changing either the 7 or the 2 from an int into a double. We can do this by saying: