# Using Pi with scanf in C

1. Jun 26, 2014

### Parmenides

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.

2. Jun 26, 2014

### Staff: Mentor

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.

3. Jul 4, 2014

### FactChecker

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: Jul 4, 2014