截断到小数点后2位并通知用户

Truncate to 2 decimal places and Notify user

本文关键字:通知 用户 2位 小数点      更新时间:2023-10-16

做了一段时间,但似乎做不好。我知道使用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.

也许有一种更简单的方法可以做到这一点,我只是不知道。如果你需要我解释其中的任何一个,最好让我知道,我会尽力的。