简体   繁体   English

使用printf打印double的可变位数

[英]Print a variable number of digits of a double using printf

Anyone knows if it is possible to use printf to print a VARIABLE number of digits? 任何人都知道是否可以使用printf打印VARIABLE位数?

The following line of code prints exactly 2: 以下代码行正好打印2:

printf("%.2lf", x);

but let's say I have a variable: 但是我要说我有一个变量:

int precision = 2;

Is there a way to use it in printf to specify the number of digits? 有没有办法在printf中使用它来指定位数?

Otherwise I will have to write a 'switch' or 'if' structure. 否则我将不得不写一个'switch'或'if'结构。

Thanks 谢谢

It is possible: 有可能的:

#include <stdio.h>

int main() {
    int precision = 3;
    float b = 6.412355;
    printf("%.*lf\n",precision,b);
    return 0;
}

Yes, you can do that easily - 是的,你可以轻松地做到这一点 -

int precision = 2;
printf("%.*lf", precision, x);

Yes: printf("%*d", width, num) : see here: http://linux.die.net/man/3/printf 是: printf("%*d", width, num) :见: http//linux.die.net/man/3/printf

If you are using C++ you could use std::cout in combiation with ios_base::precision() : http://www.cplusplus.com/reference/ios/ios_base/precision/ 如果您使用的是C ++,可以在与ios_base::precision()组合中使用std::couthttp//www.cplusplus.com/reference/ios/ios_base/precision/

If you use C++, you can use setprecision : 如果使用C ++,则可以使用setprecision:

#include <iostream>
#include <iomanip>      // std::setprecision

int main () {
    int precision = 2;
    double f =3.14159;

    std::cout << std::setprecision(precision) << f << '\n';
    ++precision;
    std::cout << std::setprecision(precision) << f << '\n';

    return 0;
}

Output : 输出

3.1
3.14

You can read more about it here 你可以在这里阅读更多相关信息

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

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