c++ - setprecision() 没有按预期工作

标签 c++ iomanip

我正在做一个程序,首先从用户那里获取 2 个数字(具有 float 数据类型),然后询问用户他想要将数字除以什么数字,最后将它除以那个数字和' cout<<' 它。当我计算 22/7 这是一个非理性的数字时,它编译了但没有达到标准。最多 100 位数字,它只计算了最多 30 或 40 位数字,然后其余部分用零填充。是这样的: 3.14285707473754882812500000000000000000000000000000000000000000000000000000000000000000000000000000000

这是我的代码:

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
    system("clear");
    float y;
    int z;
    float x;
    float a;
    cout << "\nHello User\n";
    cout << "\nEnter first num to be divided: ";
    cin >> x;
    cout << "\nCool!! Now enter the 2nd number: \n";
    cin >> y;
    cout << "\Exelent!! Enter the place upto which u wanna caculate: ";
    cin >> z;
    a = x / y;
    cout << fixed << showpoint;
    cout << setprecision(z);
    cout << "Calculating......\n" << a << endl;
    return 0;
}

最佳答案

浮点类型有一定的精度。在 float (或 double )上操作时,您不会得到准确的结果。现在要获得更好的精度,请使用 double而不是 float (有关详细信息,请参阅 this post)。

你可以 #include <limits> ,删除从输入中获取精度的步骤并将代码更改为:

std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);

以您使用的类型的最高精度显示结果。

关于c++ - setprecision() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42293545/

相关文章:

c++ - 在数字前面添加 0

c++ - 在 C++ 中,它是从小数点开始还是从整个 #setprecision 开始

c++ - Rcpp 中 "List"的操作函数 - 类似于 R 中的 "Reduce function"

c++ - Boost ASIO - 获取排序的端点(首先是 IPv4,然后是 IPv6)

c++ - 同时替换多个字符

C++ iomanip 对齐

c++ - std::hex 无法处理负数?

c++ - I/O 操纵器错误或 const ref 的临时生命周期延长?

c++ - Unresolved inclusion <GL/glut.h>

c++ - 如何重新定位/调整屏幕上的资源?