简体   繁体   English

setprecision + fixed - 打印值没有不必要的零

[英]setprecision + fixed - printing value without unnecessary zeros

The following code:以下代码:

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

prints: 3.140000, 3.141593打印数:3.140000、3.141593

I want to print values without unnecessary zeros: 3.14, 3.141593 How to do that without using the string and stringstream classes ?我想打印没有不必要的零的值:3.14, 3.141593 如何在不使用 string 和 stringstream 类的情况下做到这一点?

When neither fixed nor scientific format is chosen, the meaning of setprecision is the number of all digits to output (not just after the dot).当既没有选择固定格式也没有选择科学格式时, setprecision的含义是要输出的所有数字的数量(不仅仅是点之后)。

Therefore, this should work for you因此,这应该适合你

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

Output:输出:

3.14, 3.141593

You may use cmath to count the digit of integer parts as shown:您可以使用cmath计算整数部分的位数,如下所示:

but if number small than 0.1 will be wrong但如果数字小于 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM