如何在不丢失第一位数字的情况下打印出双精度值

How to print out a double value without losing first digit

本文关键字:情况下 打印 双精度 数字 第一位      更新时间:2023-10-16

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

我已经以更简单的方式尝试过它并且它奏效了。而且我没有看到任何问题会弄乱我的代码中的替身。

#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。

其他答案中涵盖的问题:读取'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 。如果未"q" string,请尝试将其转换为带有 std::stodstd::istringstreamdouble

当您在命令行中键入 1.95 时,变量 user_input 被分配为 '1',price 被分配 .95。

相关文章: