#include
using namespace std;
int main(int argc, char** argv){
float result;
result=(340/101);
cout<<\"Result=\"<
In C++, the (340/101)
is considered in isolation. Since both operands of /
are int
s, the compiler generates code for integer division. Then, since you're assigning that result to a float
, it generates code to convert the resulting int
to float
.
To get floating point division, you need to ensure that (at least) one of the operands to /
starts out as a float
(or double
), such as: float result = 340.0f / 101.0f;
340
is an integer and 101
is an integer, so 340/101
performs integer division. The result of the division is converted to a float
when it is assigned to result
.
You need to cast one to a floating point type to have floating point division performed:
result = static_cast<float>(340)/101;
or just use a floating literal:
result = 340.0f/101;
Because the expression (340/101)
is evaluated independent of its surrounding context. int/int
always results in an int
. It makes no difference if you store that int
in a float
variable later on.
It's due to integer division, as both operands in the division operation are integers. Either cast one of the numbers to a float, or utilize floating point syntax:
result = (340.0 / 101.0)