c++ - 如何在不丢失第一个数字的情况下打印出双精度值
问题描述
当我运行我的代码时,它只打印双精度的小数部分。在另一页上,我取了一个输入的双精度并以输入的方式打印出双精度。但是对于我下面的代码,它只打印出小数。例如,当我输入 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。
解决方案
其他答案中涵盖的问题:在'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"
,尝试将其转换为double
withstd::stod
或 an std::istringstream
。
推荐阅读
- sql - org.apache.spark.sql.AnalysisException:表达式 't2.`sum_click_passed`' 既不在 group by 中,也不是聚合函数
- reactjs - serializer.is_valid() 返回 500 内部服务器错误
- c++ - C++ - 自动返回引用和非引用类型
- laravel - 通过 htaccess 文件将主域重定向到文件夹 Cpanel
- css - 如何在粘性广告中自定义关闭按钮
- reactjs - 如何为不同的用户显示不同的用户界面?
- c++ - 如何让 GCC 创建额外的自定义部分?
- javascript - 每当单击按钮时,如何在循环中使用不同的参数执行相同的功能
- python - 无法使用 tex 处理字符串,因为找不到乳胶
- date - 如何使用日期间隔初始化 Tabulator 表?