Why function will not change variable?

后端 未结 2 666
逝去的感伤
逝去的感伤 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: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 
    
    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.

提交回复
热议问题