Home > Software design >  When I assign int to float variable, then I print the variable. Why the output is 1 but not 1.0?
When I assign int to float variable, then I print the variable. Why the output is 1 but not 1.0?

Time:11-15

#include <iostream>
int main()
{
    float i = 1;
    std::cout << i;
    return 0;
}

I read C Primer, it said when we assign int to float variable, the fractional part is recorded as 0. Then I try the code above, I couldn't understand the output.

CodePudding user response:

Well, it's up to std::cout to print that 0 or not, not i itself. std::cout choose to not print that 0, so all you can see is 1.

You can change it using <iomanip>'s std::setprecision():

#include <iostream>
#include <iomanip>

int main()
{
    float i = 1;
    std::cout << std::fixed << std::setprecision(1) << i;
    return 0;
}

This above prints:

1.0

CodePudding user response:

Why the output is 1 but not 1.0?

Because you didn't specify such formatting, and because that's not how floats are formatted by default. You can change the formatting using io manipulators.

CodePudding user response:

  You could try to use printf to write a formatted number to stdout.

#include <iostream>

int main()
{
    float i = 1;
    printf("%lf", i);
    
    return 0;
}

  output:

1.000000

  •  Tags:  
  • c
  • Related