0

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

4

2 回答 2

6

您没有存储返回值。改变:

get_length(length);

至:

length = get_length(length);

length当你这样做时,没有必要通过。

另一种方法是传递一个地址:

#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);
}

请注意%f,not是in%lf的正确格式说明符。但是,使用是正确的。doubleprintf()%lfscanf()

于 2013-10-20T22:10:12.213 回答
3

C 是“按值传递”,这意味着该值实际上是被复制进来的。因此通过使用引用更改值实际上并不会更改原始引用。

有两种方法可以解决这个问题:

1)存储到本地值,然后捕获返回值:

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

2)传递一个指针:

get_length(&length)
...
double get_length(double *length)
{
    printf("What is the rectangle's length?\n");
    scanf("%lf", length);
}
于 2013-10-20T22:13:16.937 回答