如何打印没有小数或科学记数法c ++的整数

时间:2017-04-11 15:10:16

标签: c++ format

我正在尝试使用std :: cout<<

打印以下内容
  

256 6561 65536 390625 1679616 5764801 16777216 43046721 100000000

然而,如果我使用它,我会得到科学记数法:

#include <math.h>
for (int k = 2; k <=10; ++k)
    std::cout<< " " << pow(k, 8); //k to the power of 8
  

256 6561 65536 390625 1.67962e + 06 5.7648e + 06 1.67772e + 07 4.30467e + 07 1e + 08

如果我使用std :: fixed,我会得到不需要的小数:

for (int k = 2; k <=10; ++k)
    std::cout<< std::fixed << " " << pow(k, 8);
  

256.000000 6561.000000 65536.000000 390625.000000 1679616.000000 5764801.000000 16777216.000000 43046721.000000 100000000.000000

打印全长整数需要做什么?

3 个答案:

答案 0 :(得分:2)

pow返回浮点值,当它变大或变小时,以科学计数形式显示。转换为足够大的整数,以便显示为整数。

#include <cmath>
#include <iostream>
int main()
{
    for (int k = 2; k <= 10; ++k)
        std::cout << " " << static_cast<int>(pow(k, 8));
}

可生产

  

256 6561 65536 390625 1679616 5764801 16777216 43046721 100000000

答案 1 :(得分:2)

看起来你还没有充分利用std :: cout功能。

Streams具有格式标志,用于确定如何将值发送到显示器。

#include <iostream>
#include <math.h>

int main(int argc, const char * argv[]) {

    // 2^64 is 18,446,744,073,709,551,616 without the ','s is 20 places.
    std::cout.precision(20);


    for (int k = 2; k <=10; ++k)
        std::cout<< " x = " << pow(k, 8); //k to the power of 8

    std::cout << std::endl;


    return 0;
}

答案 2 :(得分:0)

好的,所以我实际上找到了我的问题的答案,但我会保留它,因为它可能对其他人有用。

pow(a, b);

返回nwp建议的“双浮点”。 因此,std :: fixed在避免科学记数法方面正常工作,并且简单:

static_cast<int>(pow(k, 8));

解决问题