int main()
{
float x = 45.878745645464;
std::cout << std::fixed << std::setprecision(2);
std::cout << x << '\n';
return x;
}
In the above code I have to return the x value to other function. By doing so, The value x is not updated.
It still says x = 45.878745645464. How to return the value after using setprecision?
You don't. fixed/setprecision are for stream insertion only (<<). You use them when you want to display the numbers or output to a file stream etc.
Due to how floating point numbers are stored internally, you can't insist upon a specific value (the same way you can't insist upon a specific value for say 1 / 3).
There are ways to do this such as (int)(x * 100) / 100.0 which multiples the number by 100, casts to an int to remove any more decimals and then divides by 100 to get the 2DP - but usually this again would be something done for output.
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
usingnamespace std;
void newround( float &x, int factor, int &front, int &back )
{
longlong temp = (longlong)( factor * x + 0.5 - ( x < 0 ) );
front = temp / factor;
back = abs( temp ) % factor;
x = (float)temp / factor; // This is NOT exact due to finite precision
}
int main()
{
float x = 45.878745645464; // Excessive precision for a float
cout << fixed << setprecision(2) << x << '\n';
printf( "%.2f\n", x );
int front, back;
newround( x, 100, front, back );
cout << front << "." << back << '\n';
cout << x << '\n';
}
You could also insert (with the relevant precision) into a stringstream, then take the resulting string and convert it to a float.