Reading fractions in C

后端 未结 6 484
臣服心动
臣服心动 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:40

    Alright. I've got a different way. Use strtol which will return to you a pointer to the '/' to which you add 1 and call strtol again for the second half.

    This is twice as fiddly as the first answer, halfway as fiddly as the second. :)

    #include 
    #include 
    
    int main(){
        char *f = " 12/7 ";
        char *s;
        long n,d;
        n = strtol(f, &s, 10);
        d = strtol(s+1, NULL, 10);
        printf(" %ld/%ld \n", n, d);
        return 0;
    }
    

    To answer the rest of your question, you definitely need 2 variables if it's going to be a fraction. If you can use floating-point internally and the fractions are just a nice feature for user input, then you can go ahead and divide them and store the number in one variable.

    double v;
    v = (double)n / d;
    

    The cast to double is there to force a floating-point divide upon the two integers.

    If, on the other hand you're going to have a lot of fractions to work with, you may want to make a structure to hold them (an object, if you will).

    struct frac {
        long num;
        long den;
    };
    struct frac f = { 12, 7 };
    printf("%ld/%ld\n", f.num, f.den);
    

提交回复
热议问题