c语言控制科学计数法指数位数,控制科学计数法的指数位数
默認情況下,用科學計數(shù)法表示實數(shù),輸出的指數(shù)位數(shù)為3。如何控制使其只輸出2位指數(shù)位?VC6下如何?VC2005又如何?
在VC2005下,運行庫提供一個函數(shù)_set_output_format可以控制printf輸出的實數(shù)的指數(shù)位,要輸
出2位指數(shù)位需要這樣設置:
unsigned int? old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
使用完恢復原來設置:
_set_output_format(old_exponent_format);
在VC6中沒有此函數(shù),相同功能的函數(shù)我也沒有發(fā)現(xiàn)。
在C++標準庫中的stream中,我也沒有找到這樣的格式控制符。為了在VC6下完成此功能,最后只能
選擇曲線救國的道路了——刪除一個0。
1、對于printf這樣的輸出解決方法:
void EraseZeroPlus(std::string& str, string::size_type pos)
{
string::size_type pos1= str.find("E+", pos);
if(pos1 == string::npos)
return;
pos1 +=2;
str.erase(pos1, 1);
EraseZeroPlus(str, pos1);
}
void EraseZeroMinus(std::string& str, string::size_type pos)
{
string::size_type pos1= str.find("E-", pos);
if(pos1 == string::npos)
return;
pos1 +=2;
str.erase(pos1, 1);
EraseZeroMinus(str, pos1);
}
void EraseZero(char* szBuf, FILE* pFile)
{
string str(szBuf);
EraseZeroPlus(str, 0);
EraseZeroMinus(str, 0);
fputs(str.c_str(), pFile);
}
2、對于stream這樣的輸出解決方法:
這里只是考慮輸出文件的情況。
.h file
template >
class my_ofstream : public std::basic_ofstream<_e _tr>
{
public:
my_ofstream(){m_nPrecision = 5}
explicit my_ofstream(const char *_S,
ios_base::openmode _M = out | trunc)
: std::basic_ofstream<_e _tr>(_S, _M)
{
m_nPrecision = 5;
}
void set_precision(int nPre)
{
m_nPrecision = nPre;
}
int get_precision(void)
{
return m_nPrecision;
}
virtual ~my_ofstream(){}
private:
int m_nPrecision;
};
typedef my_ofstream myofstream;
// overload operator for double and float value
myofstream& operator<< (myofstream& strm, float value);
myofstream& operator<< (myofstream& strm, double value);
.cpp file:
void erase_one_zero(std::string& str)
{
using namespace std;
string::size_type pos= str.length() - 3;
str.erase(pos, 1);
}
myofstream& operator<< (myofstream& strm, const float value)
{
using namespace std;
ostringstream oss;
oss << scientific << showpoint << setprecision(strm.get_precision()) << value;
std::string str(oss.str());
erase_one_zero(str);
strm << str;
return strm;
}
myofstream& operator<< (myofstream& strm, const double value)
{
using namespace std;
ostringstream oss;
oss << scientific << showpoint << setprecision(strm.get_precision()) << value;
std::string str(oss.str());
erase_one_zero(str);
strm << str;
return strm;
}
test code:
int main(int argc, char* argv[])
{
using namespace std;
myofstream fout("out.txt");
fout << "out put scientific format: /n";
fout << 3654.002 << endl;
fout << 0.145f << endl;
fout.set_precision(6);
fout << 3654.002 << endl;
fout << 0.145f << endl;
return 0;
}
VC6下,不知還有沒有更好的辦法……
總結
以上是生活随笔為你收集整理的c语言控制科学计数法指数位数,控制科学计数法的指数位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android com.squareup
- 下一篇: if-else多级嵌套,输入3/4/5个