How to stop large float numbers from being output in exponential form. (scientific notation?)
I have a program that calculates population growth. It seems to be working but after when the population exceed 1 million it is output as a decimal number raised to a power of ten. (is this called scientic notation? exponential form? i for开发者_运维百科get.)
Is there anyway to output the data as a full number? Here is the code for the output where I will have to convert it.
#include "header.h"
void output (float currentPopulation, float years, float birthRate, float deathRate)
{
cout << "the populaion in " << years << " years will be: " << estimatedPopulation (currentPopulation, years, birthRate, deathRate) << endl;
}
New code:
#include "header.h"
void output (float currentPopulation, float years, float birthRate, float deathRate)
{
cout << "the populaion in " << years << " years will be: " << fixed << setprecision(0) << estimatedPopulation (currentPopulation, years, birthRate, deathRate) << endl;
}
The std::fixed
manipulator, used in conjunction with std::setprecision
should help you (remember to #include <iomanip>
).
i suggest reading about std::scientific
: http://msdn.microsoft.com/en-us/library/szb722da(VS.71).aspx
With float you only have 24 bits of precision which is about 16,777,216. If you are dealing with numbers greater than that and you need more precision consider using double
though I think you will still have to do some formatting to get it to looks the way you want. In which case I recommend you look at http://www.arachnoid.com/cpptutor/student3.html and http://www.fredosaurus.com/notes-cpp/io/omanipulators.html.
cout << fixed << estimatedPopulation (currentPopulation, years, birthRate, deathRate)
float v(1234567891000000.0f);
cout.precision(0);
cout << fixed << v << endl;
Note loss of accuracy inherent in float: output is
1234567948140544
Use printf instead, like printf("%f", myvalue)
.
精彩评论