0

In this basic C++ program why can't you print out the constant Pi?

#include <iostream>
using namespace std;
#define Pi 3.1415;

int main() {
cout << Pi << endl;
return 0;
} //main
user123
  • 25
  • 2

4 Answers4

5

Your Pi definition contains a semi-colon, ;.

Upon substitution, the compiled code is

cout <<  3.1415; << endl;

When it should be

cout <<  3.1415 << endl;

In other words, do

#define Pi 3.1415

Without the semi colon.


Though, better still is to not use #define for things like this.

See for example How to use the PI constant in C++ for suggestions.

Community
  • 1
  • 1
swalog
  • 4,403
  • 3
  • 32
  • 60
1

Your Pi definition is a macro not a constant and it expands to a superfluous ; in your output statement

#define Pi 3.1415; // <<

will become

cout << 3.1415; << endl;
           // ^

and you end up with a compilation error.

To declare a constant correctly in C++, you should write

const double Pi = 3.1415;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

You need to remove ; after 3.1415. The code

#define Pi 3.1415;

implies that whenever you use Pi, it will be replaced by 3.1415;. Notice how the semicolon also gets included along with the double. So when you use cout<<Pi<<endl, the compiler reads it as cout<<3.1415;<<endl, which you can see will give an error.

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
0

Remove the semicolon from macro definition

#define PI=3.142
James Elderfield
  • 2,389
  • 1
  • 34
  • 39
ashwini
  • 142
  • 8