【问题标题】:How to show numbers in cout without the "e" notation?如何在没有“e”符号的情况下在 cout 中显示数字?
【发布时间】:2021-11-06 05:31:28
【问题描述】:

我尝试打印数字的“幂表”,但不使用“e”格式显示它们,但我不知道出了什么问题。这是我的程序:

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

int main() {
    double num [11][11];
    for (int i=0; i<=10; i++)
    {
        cout << "\t^" << i;
    }
    cout << endl;

    for (int row=1; row<=10; row++)
    {
        cout << row << "\t";
        for (int col=0; col<=10; col++)
        {
            num [row][col] = pow (row,col);
            cout << num [row][col] << "\t"; 
        }
        cout << endl;
    }
    return 0;
}

【问题讨论】:

    标签: c++ formatting pow


    【解决方案1】:

    您可以使用setiosflags functionstd::ios_base::fixed 作为其参数来指定应该使用科学记数法(使用'e');您还(很可能)需要使用0 的参数调用setprecision

    main 函数的开头附近添加这一行:

        std::cout << std::setiosflags(std::ios_base::fixed) << std::setprecision(0);
    

    请务必将#include &lt;iomanip&gt; 添加到您的代码中。另请注意,当数字中的数字多于制表位的宽度(通常为 8 个字符)时,使用这种(固定)输出格式会弄乱您的表格。不过,处理此类情况是一个稍微不同的问题。一种方法是为每列添加 两个 选项卡,仅在第一列打印第二个选项卡,或者如果前一列中的值少于 8 位;像这样(假设每个制表位 8 个字符):

    #include <iostream>
    #include <cmath>
    #include <iomanip>
    
    int main()
    {
        std::cout << std::setiosflags(std::ios_base::fixed) << std::setprecision(0);
        double num[11][11];
        for (int i = 0; i <= 10; i++) {
            std::cout << "\t\t^" << i; // Two tabs per column
        }
        std::cout << std::endl;
        for (int row = 1; row <= 10; row++)
        {
            std::cout << row << "\t";
            for (int col = 0; col <= 10; col++)
            {
                num[row][col] = pow(row, col);
                if ((col == 0) || (num[row][col-1] <= 9999999)) std::cout << "\t"; // Need the extra tab
                std::cout << num[row][col] << "\t";
            }
            std::cout << std::endl;
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多