如何在不丢失第一位数字的情况下打印出双精度值
How to print out a double value without losing first digit
当我运行代码时,它只打印双精度的小数部分。在另一页上,我拿了一个输入的双精度,并按照输入的方式打印出双精度。但是对于我的以下代码,它只打印出小数。例如,当我输入 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::stod
或 std::istringstream
的double
。
当您在命令行中键入 1.95 时,变量 user_input
被分配为 '1',price
被分配 .95。
相关文章:
- 如何在没有打印语句的情况下报告用户输入错误
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 如何在不将其拆分为两个嵌套循环的情况下打印整个形状?
- 如何在 c++ 中有效使用容器的情况下打印 5 个值的最大索引
- 为什么在 var 未更新的情况下使用,仅在启动 var 后打印
- 如何在不丢失第一位数字的情况下打印出双精度值
- 为什么在这种情况下打印错误
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- GDB有没有办法在不省略模板参数的情况下打印类型
- 要在不使用cout的情况下打印某些内容,请使用printf或puts()
- 有没有办法在不重载<<运算符的情况下打印出 std::list 的内容?
- gdb在选项卡完成的情况下打印变量时冻结
- 一种在不使用额外空间的情况下以三角波形式打印从1到n的数字的程序
- 如何在不使用迭代器的情况下在 C++ 中打印地图
- 无法在前面有多余空格的情况下获取要打印的数组.只有第一个值会用空格打印
- 在不引入包装的情况下打印一对
- 如何在不使用分号的情况下打印分号(;)
- 在不附加GDB的情况下打印所有线程的堆栈跟踪
- 如何在不刷新缓冲区的情况下打印换行符