整数值在 setprecision() 中没有精度 [duplicate]

Integer value not having precision with setprecision() [duplicate]

提问人:Chaserix 提问时间:9/29/2023 最后编辑:cigienChaserix 更新时间:9/29/2023 访问量:100

问:

我这里有一个程序,用一个系列来近似 pi 的值,并且需要它以一定的精度输出 pi,我选择了 16 位数字。但是,当我输入 0 进行求和时,它返回 4(这是正确答案),但没有小数。其余输入的精度为 16。

#include <iostream>
#include <iomanip>
#include <string>

using std::cin;
using std::cout;
using std::endl;

int myPrompt(void);
double mySum(int);
void myResults(void);

int main() {
    myResults();
    return 0;
}


int myPrompt(void) {
    cout << "Approximating pi using the Madhava-Leibniz series" << endl
         << std::setfill('=') << std::setw(std::size("Approximating pi using the Madhava-Leibniz series")) << "" << endl;
    int input;
    do {
        cout << "Please input an integer greater than or equal to 0: ";
        cin >> input;
    } while (input < 0);
    return input;
}

double mySum(int input) {
    double numerator = -1;
    double output = 0;
    int base = -1;
    for (int k = 0; k <= input; k++) {
        numerator *= base;
        output += numerator / ((2 * k) + 1);
    }

    return (output * 4);
}

void myResults(void) {
    int userInput = myPrompt();
    double output = mySum(userInput);
    cout << std::setprecision(16) << "The approximated value of pi is: " << output << endl;
}

我尝试将多个变量类型设置为双精度,假设它只是返回一个整数,但我似乎找不到原因。我只需要它以 4 位精度输出 16 位。任何帮助都值得赞赏,谢谢!

C++ 精度

评论

1赞 Some programmer dude 9/29/2023
尝试使用浮点格式操纵器
0赞 molbdnilo 9/29/2023
默认情况下不打印尾随零。(4.0 和 4.00000 与 4 相同。
0赞 n. m. could be an AI 9/29/2023
stackoverflow.com/questions/17341870/......

答:

8赞 Ada 9/29/2023 #1

我认为问题在于如何显示浮点数。使用 设置精度时,它会影响显示的小数位数,但不能保证所有 16 位小数都显示为零。std::coutstd::setprecision(16)

除了设置精度外,还可以使用:std::fixedstd::showpoint

void myResults(void) {
    int userInput = myPrompt();
    double output = mySum(userInput);
    cout << std::fixed << std::showpoint << std::setprecision(16) << "The approximated value of pi is: " << output << endl;
}