c - 未初始化的变量

标签 c function variables

我正在尝试编写两个函数,一个函数接受输入,另一个函数计算加速度。编译器告诉我,我的变量尚未初始化,但它们应该具有来自输入的值。我做错了什么。

#include <stdio.h>
#include <stdlib.h>

void input_instructions(double vi, double vf);
double compute_acceleration(double vi, double vf);

int main()
{
    double vi;
    double vf;
    double acc;
    double t;


    input_instructions(vi, vf);

    acc = compute_acceleration(vi,vf);

    t = (vf - vi)/acc;

    printf("The constant acceleration of the cyclist is %.2f and it will take him %.2f minutes/seconds/"
            "to come to rest with an initial velocity of 10mi/hr.\n", acc, t);
}

void input_instructions(double vi, double vf)
{
    printf("This program will calculate the rate of accleration and the time it takes/"
            "the cyclist to come to rest\n");
    printf("Enter inital velocity=>");
    scanf("%lf", &vi);
    printf("Enter final velocity");
    scanf("%lf", &vf);
}

double compute_acceleration(double vi, double vf)
{
    double t = 1;
    double a = (vf-vi)/t;
    return (a);
}

最佳答案

哇,这里发生了很多糟糕的事情。除了 main() 中声明的未初始化变量(是的,编译器是正确的)C 按值传递参数。 vi 和 vf 参数存储在堆栈中。然后你的 scanf 获取该堆栈变量的地址,为其分配一个值,函数返回,分配的值就消失了 - 噗!

void input_instructions(double vi, double vf)
{
    printf("Enter inital velocity=>");
    scanf("%lf", &vi);
    printf("Enter final velocity");
    scanf("%lf", &vf);

    // function returns and input parameter values are gone.
 }

您想要将指针传递给变量,如下所示:

void input_instructions(double *vi, double *vf)
    {
        printf("This program will calculate the rate of accleration and the time it takes/"
                "the cyclist to come to rest\n");
        printf("Enter inital velocity=>");
        scanf("%lf", vi);
        printf("Enter final velocity");
        scanf("%lf", vf);

并从 main() 调用,如下所示:

   input_instructions(&vi, &vf);

参见examples .

关于c - 未初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626828/

相关文章:

c - 有没有C的替代品?

c - 了解 C 中的取消引用、地址和数组下标运算符

c - 附加字符串的函数返回指针/转换错误

python - 如何通过名称获取函数对象?

php - 尝试使用查询变量和表单数据来更改数据库中的表

delphi - Delphi中For循环后的循环变量是什么?

java - 根据其他变量设置变量值

c - 对哈希表进行排序 Glib - qsort

const double *bar = (const double *) foo;?

php - 将自定义 MySQL 查询移至 PHP 中