Dividing two integers to produce a float result

C++PrecisionInteger Division

C++ Problem Overview


> 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

C++ Solutions


Solution 1 - C++

Cast the operands to floats:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjwbensleyView Question on Stackoverflow
Solution 1 - C++cdigginsView Answer on Stackoverflow