Why function will not change variable?

后端 未结 2 665
逝去的感伤
逝去的感伤 2020-12-22 12:05

In this code I seem to get zero, I\'m not too familiar with as to why I can\'t change the variable length with the function I created. Any help could be useful.



        
相关标签:
2条回答
  • 2020-12-22 12:39

    C is "pass-by-value", which means the value is actually copied in. So changing the value by using the reference doesn't actually change the original reference.

    There are two ways around this:

    1) store to a local value and then capture the return value:

    length = get_length()
    ...
    double get_length()
    {
        double a;
        printf("What is the rectangle's length?\n");
        scanf("%lf", &a);
        return a;
    }
    

    2) pass a pointer:

    get_length(&length)
    ...
    double get_length(double *length)
    {
        printf("What is the rectangle's length?\n");
        scanf("%lf", length);
    }
    
    0 讨论(0)
  • 2020-12-22 12:53

    You're not storing the return value. Change:

    get_length(length);
    

    to:

    length = get_length(length);
    

    There's no need to pass length when you do this.

    The other way to do it is to pass an address:

    #include <stdio.h>
    
    void get_length(double * a);
    
    int main(int argc, char* argv[]) {
        double length = 0;
        get_length(&length);
        printf("%f", length);
        return 0;
    }
    
    void get_length(double * a) {
        printf("What is the rectangle's length?\n");
        scanf("%lf", a);
    }
    

    Note that %f, not %lf, is the correct format specifier for a double in printf(). Using %lf is correct for scanf(), however.

    0 讨论(0)
提交回复
热议问题