0

setprecision(2) 和字段宽度操纵器不起作用。当我执行双减法时,它会将数字四舍五入到小数。并且输入不正确或字段宽度为 6。我做错了什么?

//Runs a program with a menu that the user can navigate through different options with via text input

#include <iostream>
#include <cctype> 
#include <iomanip>
using namespace std;

int main()
{
    char userinp;
    while (true)
    {   
        cout<<"Here is the menu:" << endl;
        cout<<"Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)" << endl;

        cin >> userinp;
        userinp = tolower(userinp);

        if (userinp == 'h')
        {   
            cout <<"This is the help menu. Upon returning to the main menu, input A or a to add 2 intergers." << endl;
            cout <<"Input D or d to subtract 2 doubles. Input Q or q to quit." << endl;
        }

        else if (userinp == 'a')
        {
            int add1, add2, sum;
            cout <<"Enter two integers:";
            cin >> add1 >> add2;
            sum = add1 + add2;
            cout << setw(6) << setiosflags(ios::right) << "The sum of " << add1 << " + " << add2 << " = " << sum << endl;
        }
        else if (userinp == 'd')
        {
            double sub1, sub2, difference;
            cout.fixed;
            cout <<"Enter two doubles:";
            cin >> sub1 >> sub2;
            difference = sub1 - sub2;
            cout << setw(6) << setiosflags(ios::right) << setprecision(2) << "The difference of " << sub1 << " - " << sub2 << " = " << difference << endl;
        }
        else if (userinp == 'q')
        {
            cout <<"Program will exit, goodbye!";
            exit(0);
        }
        else
        {
        cout <<"Please input a valid character to navigate the menu - input the letter h for the help menu";
        cout << "Press any key to continue" << endl;
        }

    }
}
4

2 回答 2

0

为了改进 Dietmar 的答案,为了获得小数点后两位数,您需要

cout << std::right << std::fixed << std::setprecision(2) << "The difference of "
     << std::setw(6) << sub1 << " - "
     << std::setw(6) << sub2 << " = "
     << std::setw(6) << difference << '\n';

添加std::fixed解决了您遇到的问题。

示范:

Here is the menu:
Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)
d
Enter two doubles:123.456
23.4
The difference of 123.46 -  23.40 = 100.06
Here is the menu:
Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)
于 2013-10-01T23:49:28.380 回答
0

width()是唯一不粘的操纵器:它适用于下一个格式化输出,在您的情况下适用于字符串文字的打印。您应该std::setw()在要格式化的值之前使用 right ,例如:

cout << std::right << std::setprecision(2) << "The difference of "
     << std::setw(6) << sub1 << " - "
     << std::setw(6) << sub2 << " = "
     << std::setw(6) << difference << '\n';

我不确定您在精度方面指的是什么。您可能还想使用std::fixed.

于 2013-10-01T23:39:56.583 回答