Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Need help making this code more easy to understand

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 509
    Answer it

    Given are the following three functions on integers:
    f(x) = x2 g(x) = x + 1 h(x) = x  - 1
    Implement these functions in C. Next, write a program that accepts on its input an integer n
    followed by a series of letters f, g, and h terminated by an equals sign (=).

    The output should be the number that is the output that is obtained by applying the given sequence of functions
    to the input number. For example, the calculation of f(g(f(h(42)))) is specified by the input
    42 hfgf=. The output should be 2829124 because f(g(f(h(42)))) = f(g(f(41))) =
    f(g(1681)) = f(1682) = 2829124.

    Example 1:
    input:
    42 hfgf=
    output:
    2829124

    Example 2:
    input:
    1 fgh=
    output:
    1

    Example 3:
    input:
    -1 fgh=
    output:

     

    This is the solution to this:

    #include <stdio.h>
    
    long f(size_t x) { return x * x; }
    long g(size_t x) { return x + 1; }
    long h(size_t x) { return x - 1; }
    
    long doMath(char func, size_t x) {
        long value;
    
        switch(func) {
            case 'f':
                value = f(x);
                break;
            case 'g':
                value = g(x);
                break;
            case 'h':
                value = h(x);
                break;
        }
    
        return value;
    }
    
    int main() {
        char input[50];
    
        printf("Input: "); fgets(input, 50, stdin);
    
        int _i = 0, _j = 0;
        int num = 0; char funcs[10];
        long value;
    
        while (input[_i] != '=') {
            int c = input[_i];
    
            /* 0-9 */
            if (c >= 48 && c <= 57) {
                num *= 10; num += c - 48;
            }
            /* lowercase a-z */
            if (c >= 97 && c <= 122) {
                funcs[_j++] = (char)c;
            }
    
            _i++;
        }
    
        value = num;
    
        for (_j = 0; funcs[_j] != '\0'; _j++) {
            value = doMath(funcs[_j], value);
        }
    
        printf("Output: %li\n", value);
    }

     

    Now I need help to make the code more easy to understand and in c++ not c#. Can someone help me?

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: