Iomanip setprecision() 方法仅在第一行无法正常工作,为什么?

Iomanip setprecision() Method Isn't Working as It Should Only on the First Line, Why?

所以我正在编写一个程序来计算使用时钟的函数的执行时间,我使用 iomanip 将输出更改为带有 9 个零的十进制。

这是我正在使用的代码:

#include <time.h>
#include <iomanip>

using namespace std;

void linearFunction(int input)
{
    for(int i = 0; i < input; i++)
    {

    }
}

void execution_time(int input)
{
    clock_t start_time, end_time;

    start_time = clock();
    linearFunction(input);
    end_time = clock();

    double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC);
    cout << "Time taken by function for input = " << input << " is : " << fixed
         << time_taken << setprecision(9);
    cout << " sec " << endl;
}

int main()
{
    execution_time(10000);
    execution_time(100000);
    execution_time(1000000);
    execution_time(10000000);
    execution_time(100000000);
    execution_time(1000000000);

    return 0;
}

并且输出显示:

Time taken by function for input = 10000 is : 0.000000 sec
Time taken by function for input = 100000 is : 0.001000000 sec
Time taken by function for input = 1000000 is : 0.002000000 sec
Time taken by function for input = 10000000 is : 0.038000000 sec
Time taken by function for input = 100000000 is : 0.316000000 sec
Time taken by function for input = 1000000000 is : 3.288000000 sec

如您所见,我第一次调用该函数时,它不遵循我编写的 setprecision(9)。为什么会这样,我该如何解决?提前谢谢你。

正确查看以下行:

cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9);

看到了吗?您在打印出 time_taken 后设置精度。所以你第一次看不到 setprecision() 的结果。但对于第二次及以后,由于 setprecision() 已经执行,您将获得所需的小数位。

因此,要解决此问题,请将 setprecision() 移动到 time_taken 之前:

cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken;

..或者你也可以这样做:

cout.precision(9);
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken;

此外,请考虑不要在您的代码中使用以下行:

using namespace std;

..因为它被认为是一种不好的做法。而是每次都像这样使用 std:::

std::cout.precision(9);
std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken;

有关这方面的更多信息,请查看 why is "using namespace std" considered as a bad practice