在c++中使用setprecision

Using setprecision in C++

本文关键字:setprecision c++      更新时间:2023-10-16

我试图在c++中使用setprecision。这是我正在做的-

我有一个输出文件,我在那里写的结果-

我对function的第一次调用正确地打印了interest_rate。假设我用interest_rate=0.035调用函数,那么我得到以下输出—
Annual Interest Rate: 0.035

但是下次如果我用相同的interest_rate i.e. 0.035调用函数,我得到以下输出-

Annual Interest Rate: 0.04

我想在两种情况下得到相同的输出,为什么会发生这种情况?

编辑:-下面是代码-

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

输入文件:- input.txt

3
1000.00
0.035
120.00
5000.00
0.04
165.00
200000.00
0.055
2250.00

下面是我得到的输出文件:

Annual Interest Rate: 0.035
1         1000.00   
2         1000.00   
3         1000.00   
4         1000.00   
Annual Interest Rate: 0.04
1         5000.00   
2         5000.00   
3         5000.00   
4         5000.00   
Annual Interest Rate: 0.06
1         200000.00 
2         200000.00 
3         200000.00 
4         200000.00 
注意输入文件中的0.055如何在输出文件
中打印为0.06

一些流操纵符/标志只应用一次(例如:setw),而其他的在它们被改变之前保持有效(例如:fixedsetprecision)。

我假设,在函数的第一次调用中,您使用的是流的默认格式(不是fixed也不是scientific)和默认精度(6)。

在函数的第二次调用中(我假设您没有在另一个函数中同时更改它),格式为fixed,精度为2。