如何在计算器中将大数字表示为小数点后两位C++

How to express large numbers to two decimal places in C++ Calculator

本文关键字:小数点 C++ 两位 表示 计算器 数字      更新时间:2023-10-16

我正在尝试用C++编写一个计算器,该计算器执行/、*、-或 + 的基本功能,并显示两个小数位的答案(精度为 0.01)。

例如100.1 * 100.1应该将结果打印为10020.01但我得到-4e-171.据我了解,这是来自溢出,但这就是我首先选择long double的原因!

#include <iostream>
#include <iomanip>
using namespace std;
long double getUserInput()
{
    cout << "Please enter a number: n";
    long double x;
    cin >> x;
    return x;
}
char getMathematicalOperation()
{
    cout << "Please enter which operator you want "
            "(add +, subtract -, multiply *, or divide /): n";
    char o;
    cin >> o;
    return o;
}
long double calculateResult(long double nX, char o, long double nY)
{
// note: we use the == operator to compare two values to see if they are equal
// we need to use if statements here because there's no direct way 
// to convert chOperation into the appropriate operator
if (o == '+') // if user chose addition
    return nX + nY; // execute this line
if (o == '-') // if user chose subtraction
    return nX - nY; // execute this line
if (o == '*') // if user chose multiplication
    return nX * nY; // execute this line
if (o == '/') // if user chose division
    return nX / nY; // execute this line
return -1; // default "error" value in case user passed in an invalid chOperation
}
void printResult(long double x)
{
    cout << "The answer is: " << setprecision(0.01) << x << "n";
}
long double calc()
{
// Get first number from user
    long double nInput1 = getUserInput();
// Get mathematical operations from user
    char o = getMathematicalOperation();
// Get second number from user
    long double nInput2 = getUserInput();
// Calculate result and store in temporary variable (for readability/debug-ability)
    long double nResult = calculateResult(nInput1, o, nInput2);
// Print result
    printResult(nResult);
    return 0;
}

setprecision告诉它你想要多少位小数作为int,所以你实际上是将其设置为setprecision(0),因为0.01被截断了。在您的情况下,您希望将其设置为 2。你也应该使用std::fixed否则你会得到科学数字。

void printResult(long double x)
{
    cout << "The answer is: " << std::fixed << setprecision(2) << x << "n";
}

工作示例

这不是由于溢出,你会得到奇怪的结果。双精度可以轻松地将数字保持在您所显示的范围内。

尝试在没有设置精度的情况下打印结果。

编辑:尝试后

long double x = 100.1;
cout << x << endl;

我看到它在我的 Windows 系统上不起作用。

所以我搜索了一下,发现:

在窗口上打印长双精度

也许这就是解释。

所以我尝试了

long double x = 100.1;
cout << (double)x << endl;

效果很好。

第二次编辑:

另请参阅拉斐尔提供的此链接

http://oldwiki.mingw.org/index.php/long%20double

默认浮点表示在314.153.1e2等表示之间自动切换,具体取决于数字的大小和可以使用的最大位数。在此演示文稿中,精度是最大位数。默认情况下为 6。

您可以增加最大位数,以便您的结果可以像314.15一样呈现,也可以通过使用std::fixed操纵器强制使用这种定点表示法。对于std::fixed,精度是小数位数。

但是,对于std::fixed非常大和非常小的数字可能非常难以阅读。

setprecision()操纵器指定小数点后的位数。 因此,如果要打印100.01,请使用 setprecision(2) .

使用 setprecision(0.01) 时,值 0.01 正在转换为 int ,其值为 0

如果您实际上阅读了setprecision()的文档,那不会有什么坏处 - 它清楚地指定了一个int参数,而不是浮点参数。