How can I recognize and use pi as input in a C program?

  • Thread starter Thread starter Parmenides
  • Start date Start date
  • Tags Tags
    Pi
Parmenides
Messages
34
Reaction score
0
Hello,

I'm trying to learn C and am only a couple weeks into it. Suppose I want to write a simple code for Trapezoidal integration and want to have the user input the integration limits via use of scanf. Also, suppose I want to focus on only trig functions such that a common limit is pi. How could I have the program recognize pi as the typed input? Let's assume I'm using the <math.h> statement "#define M_PI 3.141592653589793238462643". Thanks.
 
on Phys.org
You can make two separate inputs, multiply one with pi and add them. That way, a user can easily choose 1*pi+0 as integration border.

If you want to keep a single input:
You can read the input as string and compare it to some fixed values ("pi", "pi/2", ...) or even some patterns like "pi*123.456" where 123.456 represents an arbitrary floating point number.
Alternatively, define special numbers that get interpreted as pi or multiples of pi. Like "integration from 0 to -1 means integration from 0 to pi" or whatever. Messy, but possible. Or just let the users memorize enough digits of pi :p.
 
Parmenides said:
How could I have the program recognize pi as the typed input?
I assume you mean that the text "pi" is in the input string. You can check using strstr( input_string, "pi" ). It is common to read the inputs as a string and test its contents using sscanf (the double 's' is not a typo) and strtok.

I should warn you that allowing flexibility for user inputs can open a can of worms and put you in parsing hell. It might be better for you to specify the units of the inputs (radians, degrees, or rotations.) with a prompt or documentation. Some languages have the ability to evaluate a string as code. That would let the user input an entire math formula in that language and the language can calculate the result. C does not allow that.
 
Last edited:

Similar threads

  • · Replies 14 ·
Replies
14
Views
35K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
12
Views
3K
Replies
14
Views
4K
Replies
11
Views
4K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 8 ·
Replies
8
Views
3K
Replies
4
Views
3K
Replies
18
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K