为什么函数不会更改变量? [英] Why function will not change variable?

查看:71
本文介绍了为什么函数不会更改变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我似乎得到了零,我对为什么不能使用自己创建的函数更改变量长度不太熟悉。任何帮助都可能有用。

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

打印时返回0.0000

When it prints it returns 0.0000

推荐答案

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

You're not storing the return value. Change:

get_length(length);

至:

length = get_length(length);

当您不需要传递 length

另一种方式是通过地址:

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

请注意,%f ,而不是%lf ,是 printf()中 double 的正确格式说明符。但是,对于 scanf()使用%lf 是正确的。

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

这篇关于为什么函数不会更改变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆