Kostas
Kostas

Reputation: 4176

how to print integers without decimals or scientific notation c++

I am trying to print the following ints using std::cout<<

256 6561 65536 390625 1679616 5764801 16777216 43046721 100000000

However, if I use this I get scientific notation:

#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

and if I use std::fixed, I get unwanted decimals:

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

What do I need to do to print full-length integers?

Upvotes: 1

Views: 1353

Answers (3)

Kostas
Kostas

Reputation: 4176

Ok, so I actually found the answer to my question but I'll keep it because it might be useful to other people.

pow(a, b);

returns a "double floating point" as nwp suggested. Therefore, std::fixed works correctly in avoiding scientific notation, and a simple:

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

solves the problem

Upvotes: 0

Vanderdecken
Vanderdecken

Reputation: 205

It would seem you are not fully utilizing std::cout functionality.

Streams have format flags that determine how values get sent out to the display.

#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;
}

Upvotes: 2

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

pow returns a floating point value, which is displayed in scientific notation when it becomes large or small. Cast to a sufficiently large integer so it will be displayed as an integer.

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

Produces

256 6561 65536 390625 1679616 5764801 16777216 43046721 100000000

Upvotes: 2

Related Questions