【问题标题】:How to swich back from scientific notation如何从科学记数法切换回来
【发布时间】:2014-03-30 22:29:45
【问题描述】:

我需要用科学计数法显示一个元素。 cout 位于几个循环内,设置科学计数法后,它会影响程序中的整个 cout。 如何切换回常规符号。

这是 cout 行:

cout << "Firing '" <<  fir << "' Time: " << time <<  " sec\nCorresponding altitude: " << scientific << alt << endl;

只有变量 alt 应该以科学计数法显示。

我添加了 cout.precision(2);和 cout

感谢您的帮助。

【问题讨论】:

  • 你不能在 cout 行之前定义 cout.precision(2) 然后输出该行的一部分,然后改变精度 cout.precision(10) 和输出剩下的。

标签: c++ scientific-notation


【解决方案1】:

试试这样的:

http://www.cplusplus.com/reference/ios/scientific/

cout << "Firing '" <<  fir << "' Time: " << time <<  " sec\nCorresponding altitude: ";
cout << std::scientific << alt << endl;
std::cout << std::defaultfloat; // C++ 11

...或...

std::cout.unsetf ( std::ios::floatfield );   // C++ 98

另见:

c++ std::stream double values no scientific and no fixed count of decimals

http://www.cs.duke.edu/courses/cps149s/fall99/resources/n2.html

http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/io/omanipulators.html

【讨论】:

    【解决方案2】:

    好吧,在设置精度之前,您可以将其与cout.precision() 一起存储在一个变量中。使用设置为 2 的精度完成后,重置回使用变量的位置。即cout.precision(precision) 假设“精度”是您的变量。

    示例:

    输出:

    1.2

    1.234

    #include <iostream>
    
    using namespace std;
    
    int precision;
    float number = 1.234;
    
    int  main(void)
    {
      precision = cout.precision();
      cout.precision(2);
      cout << number << endl;
      cout.precision(precision);
      cout << number << endl;
    }
    

    【讨论】:

    • 感谢您提供详细示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多