gpt4 book ai didi

c - 未初始化的变量

转载 作者:行者123 更新时间:2023-11-30 20:00:50 24 4
gpt4 key购买 nike

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

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com