Possible Duplicate:
Why can't I return a double from two ints being divided
My C++ program is truncating the output of my integer devision even when I try and place the output into a float. How can I prevent this whilst keeping those to variables (a & b) as integers?
user@box:~/c/precision$ cat precision.cpp #include <iostream> #include <iomanip> using namespace std; int main() { int a = 10, b = 3; float ans = (a/b); cout<<fixed<<setprecision(3); cout << (a/b) << endl; cout << ans << endl; return 0; } user@box:~/c/precision$ g++ -o precision precision.cpp user@box:~/c/precision$ ./precision 3 3.000
Dividing two integers will result in an integer (whole number) result. You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.
If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.
The single forward slash / operator is known as float division, which returns a floating point value.
To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.
Also, floats only have so much precision. Your integer division might require the "double precision" of a double – recursion.ninja Sep 16 '12 at 13:46 38 Strictly speaking you only need to cast one integer to float, althought this does make it extra clear.
If you want to perform floating point division, you should cast before dividing: zahl1 / i is computed as int division and then converted to Float by the Float constructor. For floating point division, cast one of the operands to float or double: It's because you're doing integer division,you need to change the int value as float at first.
Python float division uses the / operator and returns, well, a floating point value. This, perhaps, is more of how you’d expect division to work. Let’s look at a few more examples: As you can see, the results return values you’d expect, regardless of whether you’re dividing integers, floats, or a mix of both.
Since we are using C++ here, use static_cast. Note that it's possible to use the type division rule and do it simply like float ans = static_cast<float>(a)/b; – Hitokage
Cast the operands to floats:
float ans = (float)a / (float)b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With