在C ++中没有科学记数法的循环中显示特定数字时出现问题

时间:2022-01-14 09:21:30

Ok, so I'm writing a program, of which the overall purpose is not necessarily important, but there is a point in the program where I'm trying to print out a table that displays n, n!, and x^n (where n and x are both user inputs).

好的,所以我正在编写一个程序,其总体目的不一定重要,但程序中有一点我正在尝试打印出一个显示n,n!和x ^ n的表(其中n和x都是用户输入)。

The code I have thus far is as follows:

我到目前为止的代码如下:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
    float x, xn, factorial = 1;
    float n = 1;

    cout << "Enter an angle in radians: ";
    cin >> x;
    while (n <= 1)
    {
        cout << "Enter the number of terms to be included into the Taylor series expansion: ";
        cin >> n;
        if (n < 1)
        {
            cout << "Error! Try again\n";
        }
    }

    cout << "n\tn!\tx^n\t\n";
    for (int i = 1; i <= n; i++)
    {
        cout << i;
        factorial *= i;
        cout << "\t" << factorial;
        xn = pow(x, i);
        cout << "\t" << setprecision(i) << xn;
        cout << endl;

    }

    return 0;
}

Now, the problem I'm having is that it begins to display my x^n in scientific notation after it goes past 5 decimal places. I do not want it to do this. I tried using setprecision(i) as you might have noticed, but that doesn't do the job. It's confusing me because a.) I'm not sure I know the code I need to use to get it to stop displaying in scientific notation and b.) I don't want the other outputs for n and n! to be affected by the manipulation I'm going to have to use on the output of x^n, which is tricky for me because they're all calculated and outputted in the same loop. I'm at a loss here, any help is much appreciated! I'd post an image of the program output for you all, but it seems I need more reputation to do that.

现在,我遇到的问题是它在超过5位小数后开始以科学计数法显示我的x ^ n。我不希望它这样做。我尝试使用setprecision(i),你可能已经注意到了,但那不能完成这项工作。这让我感到困惑,因为a。)我不确定我是否知道我需要用它来停止以科学记数法显示的代码和b。)我不想要n和n的其他输出!受到我将要在x ^ n的输出上使用的操作的影响,这对我来说很棘手,因为它们都是在同一个循环中计算和输出的。我在这里不知所措,非常感谢任何帮助!我会为你发布一个程序输出的图像,但似乎我需要更多的声誉来做到这一点。

Also, on a side note, if you have any advice on a better way to format my table, I'd love to hear it.

此外,在旁注中,如果您对更好的格式化表格有任何建议,我很乐意听到。

1 个解决方案

#1


0  

Before you print xn, you can switch the stream to use fixed notation, and after it, switch back to default float:

在打印xn之前,可以将流切换为使用固定表示法,然后切换回默认浮点数:

cout << "\t" << setprecision(i) << std::fixed << xn << std::defaultfloat;

References: http://en.cppreference.com/w/cpp/io/manip/fixed

#1


0  

Before you print xn, you can switch the stream to use fixed notation, and after it, switch back to default float:

在打印xn之前,可以将流切换为使用固定表示法,然后切换回默认浮点数:

cout << "\t" << setprecision(i) << std::fixed << xn << std::defaultfloat;

References: http://en.cppreference.com/w/cpp/io/manip/fixed