Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Using Pi with scanf in C

  1. Jun 26, 2014 #1
    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. jcsd
  3. Jun 26, 2014 #2

    mfb

    User Avatar
    2016 Award

    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.
     
  4. Jul 4, 2014 #3

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    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
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Using Pi with scanf in C
  1. Cin or scanf? (Replies: 9)

Loading...