Reading fractions in C

后端 未结 6 489
臣服心动
臣服心动 2021-01-14 23:45

How do I read a fraction into C to do math with it? (The fraction will contain the slash symbol) For example, A user will input 3/12. (a string) The program will find the gc

6条回答
  •  执念已碎
    2021-01-15 00:49

    Here's what I generally do.

    int main()
    {
    double a,b=1.0f,s;
    scanf("%lf/%lf",a,b);
    s=a/b;
    printf("%lf",s);
    }
    

    Even if the user the doesn't enter the value of variable b the value is already initialized to 1.0f so it can calculate it's value anyway.

    This is tried on Ubuntu with GCC.

提交回复
热议问题