首页 > 解决方案 > 如何在不丢失第一个数字的情况下打印出双精度值

问题描述

当我运行我的代码时,它只打印双精度的小数部分。在另一页上,我取了一个输入的双精度并以输入的方式打印出双精度。但是对于我下面的代码,它只打印出小数。例如,当我输入 1.95 时,它只打印出 0.95。为什么要删除第一个数字?我在我的代码中看不到任何指向这一点的东西。

我已经以更简单的方式尝试过它并且它有效。而且我没有看到任何会与我的代码中的 double 混淆的问题。

#include <iostream>
using namespace std;

int main()
{
double price;
char user_input;
do
{
    cout << "Enter the purchase price (xx.xx) or `q' to quit: ";
    cin >> user_input;
    if (user_input == 'q')
    {
        return 0;
    }
    else
    {
        cin >> price;
        int multiple = price * 100;
        if (multiple % 5 == 0)
        {
            break;
        }
        else
        {
            cout << "Illegal price: Must be a non-negative multiple of 5 cents.\n" << endl;
        }
    }
} while (user_input != 'q');

cout << price << endl;
}

当我输入 1.95 时,我得到 0.95。但输出应该是 1.95。

标签: c++doublecincout

解决方案


其他答案中涵盖的问题:在'q'将流中的第一个字符解析为double.

解决方案:阅读第double一个。如果读取失败,请检查输入是否为'q'.

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    double price;
    while (true)
    {
        cout << "Enter the purchase price (xx.xx) or `q' to quit: ";
        if (cin >> price)
        {
            // use price
        }
        else // reading price failed. Find out why.
        {
            if (!cin.eof()) // didn't hit the end of the stream
            {
                // clear fail flag
                cin.clear();
                char user_input;
                if (cin >> user_input && user_input == 'q') // test for q
                {
                    break; // note: Not return. Cannot print price if the
                           // program returns
                }
                // Not a q or not readable. clean up whatever crap is still
                // in the stream
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
            }
            else

            {
                // someone closed the stream. Not much you can do here but exit
                cerr << "Stream closed or broken. Cannot continue.";
                return -1;

            }
        }
    }

    cout << price << endl;// Undefined behaviour if price was never set.
}

另一种合理的选择是将所有输入读取为std::string. 如果string不是"q",尝试将其转换为doublewithstd::stod或 an std::istringstream


推荐阅读