【问题标题】:setprecision + fixed - printing value without unnecessary zerossetprecision + fixed - 打印没有不必要零的值
【发布时间】:2013-10-21 14:47:11
【问题描述】:

以下代码:

double x = 3.14;
double y = 3.14159265359;
cout<<fixed<<setprecision(6)<<x<<", "<<y<<endl;

打印:3.140000、3.141593

我想打印没有不必要零的值: 3.14, 3.141593 不使用string和stringstream类怎么办?

【问题讨论】:

  • fixed 使流显示尾随零。不要使用它。
  • Fixed 是必要的,因为我想为数字的小数部分设置精度。没有固定我得到 3.14159
  • iostreams 没有足够复杂的操纵器来做到这一点,这真的取决于你从字符串中敲出那些零。

标签: c++


【解决方案1】:

当既没有选择固定格式也没有选择科学格式时,setprecision 的含义是要输出的所有位数(不只是点之后)。

因此,这应该适合你

double x = 3.14;
double y = 3.14159265359;
cout<<setprecision(7)<<x<<", "<<y<<endl;

输出:

3.14, 3.141593

【讨论】:

    【解决方案2】:

    您可以使用cmath 计算整数部分的位数,如图所示:

    但是如果数字小于 0.1 就会出错

    #include <iostream>
    #include <iomanip>
    #include <cmath>
    using namespace std;
    int main(){
        double a = -123.456789;
        double b = 4567.45;
        if (a > 1 || a < -1){
            cout << setprecision(5 + int(log10(fabs(a)) + 1)) << a << endl; //anser is -123.45679
        }
        else {
            cout << setprecision(5) << a << endl;    // if a = 0.0123456 answer will be 0.012347
        }
        if (b > 1 || b < -1){
            cout << setprecision(5 + int(log10(fabs(b)) + 1)) << b << endl; //anser is 4567.45
        }
        else {
            cout << setprecision(5) << b << endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      相关资源
      最近更新 更多