Mar*_*bri 3 c++ arrays string precision double
我在c ++中有一个大数字存储为精确的double值(假设输入'n'是75):2.4891e + 109
有没有办法将其转换为字符串或每个数字的数组?
到目前为止,这是我的代码,尽管它与问题并不完全相关:
int main(){
double n = 0;
cout << "Giz a number: ";
cin >> n;
double val = 1;
for(double i = 1; i <= n; i++){
val = val * i;
}
//Convert val to string/array here?
}
Run Code Online (Sandbox Code Playgroud)
dir*_*tly 14
std::stringstream str;
str << fixed << setprecision( 15 ) << yournumber;
Run Code Online (Sandbox Code Playgroud)
您可能还对scientific格式标志感兴趣.
C++ 11还有一些有趣的功能std::to_string,您可能想要查看!
标准方式有什么问题?
std::stringstream ss;
ss << val;
std::string s = ss.str();
Run Code Online (Sandbox Code Playgroud)
此外,C++ 11允许:
std::string s = std::to_string(val);
Run Code Online (Sandbox Code Playgroud)
如果您需要性能,您可能会发现上面涉及的内存分配过于昂贵,在这种情况下,您可以使用snprintf,已弃用的strstream,或者可能直接使用num_put facet.例如:
char c[30];
std::snprintf(c,sizeof c,"%e",val);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17230 次 |
| 最近记录: |