Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include <iostream>
using namespace std;
int main()
{
float va = 11 / 2;
cout << va << endl;
return 0;
}

What I have tried:

#include <iostream>
using namespace std;
int main()
{
    float va = 11 / 2;
    cout << va << endl;
    return 0;
}
Posted
Updated 10-May-20 1:14am

11 is an integer, 2 is an integer, their division is therefore an integer division. Try
C++
float va = (float)11 / 2
instead.
 
Share this answer
 
Quote:
For some reason it shows 5 and not 5.5, I used float for that purpose. Why?

The reason is very simple: in with C/C++, a division of integers is an'integer division' with integer result, thus 5 in your case, because 11 is 5*2+1.
The solution is to divide floats or cast to floats.
in your code, declaring va as float does not change the division.
C++
#include <iostream>
using namespace std;
int main()
{
    float va = 11.0 / 2.0;
    cout << va << endl;
    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900