Why function will not change variable?

2019-03-04 14:13发布

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.

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

When it prints it returns 0.0000

2条回答
在下西门庆
2楼-- · 2019-03-04 14:56

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.

查看更多
我命由我不由天
3楼-- · 2019-03-04 15:06

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);
}
查看更多
登录 后发表回答