截断到小数点后2位并通知用户
Truncate to 2 decimal places and Notify user
做了一段时间,但似乎做不好。我知道使用setprecision()来截断用户输入的值,但我不确定如何验证它并告诉用户"该值超过了小数点后2位;它正在被截断。"
void decimalFormat(string &point)
{
int decimal;
decimal = point.find('.');
if(decimal>2)
{
for(int x= decimal-2; x > 0; x -=2)
cout<<"Only two decimal places are allowed. Truncating the remainder..."<< point.erase(x);
}
}
setprecision()
实际上并没有截断用户输入,它只是在输出变量时设置小数位数。
例如:
#include <iostream>
#include <iomanip>
using namespace std;
main () {
float test = 4.556454636382;
cout << setprecision(11) << test << endl;
cout << setprecision(8) << test << endl;
cout << setprecision(2) << test << endl;
//set precision back up to 11
cout << setprecision(11) << test << endl;
}
导致
4.5564546585
4.5564547
4.6
4.5564546585
我不知道这是否回答了你的问题,但这只是对setprecision()
如何工作的一种解释,因为你看到它实际上并没有改变测试变量的值(因为即使在输出被截断后,你仍然可以选择再次显示精度为11),它只是决定了用户看到了什么。
这有助于解释你在问什么吗?
更新
所以这是一种试图解决你问题的方法,但我想我已经找到了一些办法。所以这是我认为可以解决你问题的代码,我会尽力解释它,但如果你有任何问题,请告诉我。
因此,变量"test"将通过小数点后2位的标准,但第二个变量"test2"不会。所以我所做的是将每个变量乘以1000,这意味着如果原始变量只有2个小数点,那么得到的数字(test*1000)的最后一位将是零。
因此,如果你取任何数字的剩余部分(%),其中2位小数乘以1000,它将为零。
#include <iostream>
using namespace std;
main () {
float test = 3.14;
float test2 = 3.145;
test = test * 1000;
test2 = test2 * 1000;
if ((int)test%10 != 0)
cout << "FALSE" << endl;
else
cout << "TRUE" << endl;
if ((int)test2%10 != 0)
cout << "FALSE" << endl;
else
cout << "TRUE" << endl;
}
输出
TRUE
FALSE
因此,对于您的代码
#include <iostream>
#include <iomanip>
using namespace std;
main () {
float num;
float num2;
cout << "Enter a number (maximum 2 decimal places): ";
cin >> num;
num2 = num * 1000;
if ((int)num2%10 != 0)
cout << "You have entered a number with more than 2 decimal places, your number is being truncated." << endl;
else
cout << fixed << setprecision(2) << num << endl;
}
当我在终端中尝试时输出
myterminalstuff$ ./dec Enter a number (maximum 2 decimal places): 3.14
3.14
myterminalstuff$ ./dec Enter a number (maximum 2 decimal places): 3.1456
You have entered a number with more than 2 decimal places, your number is being truncated.
也许有一种更简单的方法可以做到这一点,我只是不知道。如果你需要我解释其中的任何一个,最好让我知道,我会尽力的。
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 函数如何通知用户它基于函数原型抛出异常?
- 如何在点击通知时捕获用户的点击操作
- 用户土地访问内核土地驱动程序系统通知
- Win32 中是否有一条消息或通知来检测用户何时更改区域设置?
- 当用户在视图之间切换时,如何收到通知
- 如何在用户更改Windows中的语言键盘布局时得到通知
- 截断到小数点后2位并通知用户
- 提升async_write:如果失败,如何跟踪未发送的内容并通知客户端/用户失败的内容?
- 如何在QDataWidgetMapper中未提交更改的情况下通知用户
- 如何在用户登录/关闭或PC进入睡眠/休眠时正确通知c++ Windows服务