[c++] Dividing two integers to produce a float result

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

This question is related to c++ precision integer-division

The answer is


Cast the operands to floats:

float ans = (float)a / (float)b;

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to precision

How do you round a double in Dart to a given degree of precision AFTER the decimal point? Show two digits after decimal point in c++ Get DateTime.Now with milliseconds precision How to convert milliseconds to seconds with precision Dividing two integers to produce a float result Double precision - decimal places Changing precision of numeric column in Oracle Double precision floating values in Python? JavaScript displaying a float to 2 decimal places What is the difference between float and double?

Examples related to integer-division

How to do integer division in javascript (Getting division answer in int not float)? Dividing two integers to produce a float result Assembly Language - How to do Modulo? Why does dividing two int not yield the right value when assigned to double? Find the division remainder of a number Why is division in Ruby returning an integer instead of decimal value? Int division: Why is the result of 1/3 == 0? Integer division with remainder in JavaScript? What is the behavior of integer division? Integer division: How do you produce a double?