代码之家  ›  专栏  ›  技术社区  ›  Crystal

格式,IOMANIP,C++

  •  7
  • Crystal  · 技术社区  · 15 年前

    我正在尝试学习使用名称空间声明,而不仅仅是说“使用名称空间std”。我正在尝试将数据格式设置为小数点后两位,并将格式设置为固定格式,而不是科学格式。这是我的主文件:

    #include <iostream>
    #include <iomanip>
    
    #include "SavingsAccount.h"
    using std::cout;
    using std::setprecision;
    using std::ios_base;
    
    int main()
    {
        SavingsAccount *saver1 = new SavingsAccount(2000.00);
        SavingsAccount *saver2 = new SavingsAccount(3000.00);
    
        SavingsAccount::modifyInterestRate(.03);
    
        saver1->calculateMonthlyInterest();
        saver2->calculateMonthlyInterest();
    
        cout << ios_base::fixed << "saver1\n" << "monthlyInterestRate: " << saver1->getMonthlyInterest()
            << '\n' << "savingsBalance: " << saver1->getSavingsBalance() << '\n';
        cout << "saver2\n" << "monthlyInterestRate: " << saver2->getMonthlyInterest()
            << '\n' << "savingsBalance: " << saver2->getSavingsBalance() << '\n';
    }
    

    在visual studio 2008上,当我运行我的程序时,在得到我想要的数据之前,我得到了“8192”的输出。这是有原因的吗?

    另外,我认为我没有正确设置固定部分或小数点后两位,因为我似乎得到了科学记数法,一旦我添加了setprecision(2)。谢谢。

    3 回复  |  直到 15 年前
        1
  •  5
  •   tzaman    12 年前

    你想要 std::fixed (另一个只是将其值插入流中,这就是为什么您看到8192),而我没有看到调用 std::setprecision 在你的代码里。
    这样可以解决问题:

    #include <iostream>
    #include <iomanip>
    
    using std::cout;
    using std::setprecision;
    using std::fixed;
    
    int main()
    {
        cout << fixed << setprecision(2)
             << "saver1\n" 
             << "monthlyInterestRate: " << 5.5 << '\n' 
             << "savingsBalance: " << 10928.8383 << '\n';
        cout << "saver2\n" 
             << "monthlyInterestRate: " << 4.7 << '\n' 
             << "savingsBalance: " << 22.44232 << '\n';
    }
    
        2
  •  3
  •   Potatoswatter    15 年前

    这可能不是你要找的答案,但浮点数不适合用于财务计算,因为1/100这样的分数不能精确表示。你最好自己做格式化。这可以封装:

    class money {
        int cents;
    public:
        money( int in_cents ) : cents( in_cents ) {}
    
        friend ostream &operator<< ( ostream &os, money const &rhs )
            { return os << '$' << m.cents / 100 << '.' << m.cents % 100; }
    };
    
    cout << money( 123 ) << endl; // prints $1.23
    

    更好(?)然而,C++有一个叫做 货币区域设置类别 其中包括 money formatter 以美分作为论据。

    locale::global( locale("") );
    use_facet< money_put<char> >( locale() ).put( cout, false, cout, ' ', 123 );
    

    这应该在国际上做正确的事情,打印用户的本地货币,并在实现中隐藏小数位数。它甚至接受一分钱的零头。不幸的是,这在我的系统(mac os x)上似乎不起作用,因为它的语言环境支持通常很差。(Linux和Windows应该会更好。)

        3
  •  2
  •   jfs    15 年前
    cout << setiosflags(ios::fixed) << setprecision(2) << 1/3.;
    

    ios_base::fixed 不是操纵器它是一个值( 1 << 13 )对于ios标志。