0

Hello guys I am new in C++ I am trying to write the function to calculate the second moment of inertia and set the precision with 3 decimal places. In the output does not apply the 3 decimal places in the first call but the following 4 calls does applied. Here is my codes , please help me find the error and if possible please explain some details thank you very much !

double beamMoment(double b, double h) //the function that calculating the second moment of inertia
{
    double I;  //variables b=base, h=height, I= second moment of inertia

    I = b * (pow(h, 3.0) / 12); // formular of the second momeent of inertia


    ofs << "b=" << b << "," << "h=" << h << "," << "I="  << I  << setprecision(3) << fixed <<  endl;
    ofs << endl;


    return I;

}

int main()
{
    beamMoment(10,100);
    beamMoment(33, 66);
    beamMoment(44, 88);
    beamMoment(26, 51);
    beamMoment(7, 19);
    system("pause");
    return 0;
}

The output in my text file is as follow :

b=10,h=100,I=833333 

b=33.000,h=66.000,I=790614.000 

b=44.000,h=88.000,I=2498730.667 

b=26.000,h=51.000,I=287410.500 

b=7.000,h=19.000,I=4001.083 
2
  • 1
    Try ofs << setprecision(3) << fixed << "b=" << b << "," << "h=" << h << "," << "I=" << I << endl; Commented Jun 25, 2016 at 20:03
  • Oh i got it. Thank you very much Commented Jun 25, 2016 at 20:31

1 Answer 1

2

You have to set stream precision before printing a number.

ofs << 5.5555 << setprecision(3) << endl; // prints "5.5555"
ofs << setprecision(3) << 5.5555 << endl; // prints "5.555"

Stream operators << and >> are, in fact, methods that can be chained. Let's say we have a piece of example java code like:

dog.walk().stopByTheTree().pee();

In C++, if we'd use stream operators, it'd look like:

dog << walk << stopByTheTree << pee;

Operations on dog objects are executed from left to right, and the direction of "arrows" doesn't matter. These method names are just syntactic sugar.

Look here for more details.

Sign up to request clarification or add additional context in comments.

1 Comment

Ya I tried to put that before print the numbers and it works thank you a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.