-10

I have tried to perform this arithmetic expression from command line but it doesn't give me valid output. How do I perform the expression in the below code using the simplest skills of C++?

#include <iostream>
using namespace std;

int main()
{
    cout << " 4 * (1.0 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11) = ";
    return 0;
}
jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
DMicheal
  • 31
  • 7

2 Answers2

3

The first problem is that you are not actually preforming any calculations, you are only printing the literal equation as a string of characters. The second issue you will face is that 1/3 is integer 1 divided by integer 3. Integer division does not account for decimals. Add a decimal point to convert an integral literal to a double.

#include <iostream>
using namespace std;

int main()
{
    // Prints the equation
    cout << " 4 * (1.0 - 1./3 + 1./5 - 1./7 + 1./9 - 1./11) = ";

    // Prints the result of the equation
    cout << 4 * (1.0 - 1./3 + 1./5 - 1./7 + 1./9 - 1./11);

    return 0;
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
3

Calculation of PI is best performed using floating point data type such as double:

#include <iostream>
#include <cstdlib>
int main(void)
{
  double pi = 4.0 * (1.0 - 1.0/3.0 + 1.0/5.0 - 1.0/7.0 + 1.0/9.0 - 1.0/11.0);
  std:: cout << "PI: " << pi << "\n";
  return EXIT_SUCCESS;
}

In short, the cout facility does not evaluate text strings, it only outputs them.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154