2016-09-21 3 views
-2

두 함수를 쓰려고하는데, 하나는 입력을 받아 다른 하나는 가속을 계산합니다. 컴파일러는 내 변수가 초기화되지 않았지만 입력 값을 가져야한다고 말합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까.초기화되지 않은 변수

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

C에서 함수가 작동하는 방식이 아닙니다. https://stackoverflow.com/documentation/c/1006/function-parameters를 시도해보십시오. –

+0

조금 우둔해 보입니다. C 클래스의 어느 부분에 있습니까? 참조에 의한 포인터와 전달이 무엇인지 아십니까? –

+0

나는 우둔하다. 우리는 패스와 포인터에 대해 아직 알지 못했습니다. –

답변

3

와우, 많은 일이 벌어지고 있습니다. main()에서 선언 된 초기화되지 않은 변수를 제외하고 (예, 컴파일러가 올바름) C는 매개 변수를 값별로 전달합니다. vi 및 vf 매개 변수 이 스택에 저장됩니다. 그런 다음 scanf는 해당 스택 변수의 주소를 가져 와서 값을 할당하고 함수가 돌아가고 할당 된 값은 사라집니다.

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

과 같이() 메인에서 호출 :

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

당신은 다음과 같이 당신의 변수에 포인터를 전달하려는

input_instructions(&vi, &vf); 

examples를 참조하십시오.

+0

이렇게하면 그렇게 할 수 없습니다. –

0

vi, vf, acc 및 t를 전역 변수 (주 외부)로 선언하십시오.

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

void input_instructions(); 
double compute_acceleration(); 
double vi; 
double vf; 
double acc; 
double t; 
int main() 
{ 



    input_instructions(); 

    acc = compute_acceleration(); 

    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() 
{ 
    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 t = 1; 
    double a = (vf-vi)/t; 
    return (a); 
} 

또는 포인터를 사용하여 'input_instructions'함수에 전달할 수 있습니다.

+0

이것이 왜 투표가 실패했는지 확실하지 않습니다. 나는 글로벌 변수 솔루션이 교수가이 사례에서 찾고 있었던 것임을 의심한다. –

1

input_instructions 함수의 변수를 "전달"할 수 없도록 읽는 중입니다. 그리고 그들의 기억은 기능 내부에서 회전되기 때문에 외부에서 접근 할 수 없습니다.

하나의 옵션은 변수 vi와 vf를 main 변수 외부에서 선언하여 전역 변수로 변경하는 것입니다. input_functions의 시그너처에 넣지 않아도되며, 나머지는 괜찮을 것입니다. 당신이 주변에 전역을 통과하고 있기 때문에이 경우

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

/* Prototypes */ 
void input_instructions(); 
double compute_acceleration(double new_vi, double new_vf); 

/* Globals */ 
double vi; 
double vf; 

int main() 
{ 

, 당신도 반드시 어느 compute_acceleration 기능에 대한 매개 변수를 허용 할 필요가 없습니다 것입니다. 저는 일반적으로 글로벌을 추천하지는 않지만 여러분이 다루고있는 문제 중 가장 적은 것으로 보입니다.

또 다른 옵션은 main의 변수 vi와 vf를 0으로 초기화 한 다음 참조로 input_instructions에 전달하여 해당 값이 함수에 의해 변경 될 수 있도록하는 것입니다. 예를 들어

:

void input_instructions(double *i, double *f); 
double compute_acceleration(double x, double y); 


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


    input_instructions(&vi, &vf); 
    acc = compute_acceleration(vi,vf); 

내가 변수의 메모리 위치가 존재하고 예에서, 주에서 VI가 실제로 VI를 이외의 다른 변수 방법을 보여 곳 이해하는 데 도움이되는 변수의 이름을 변경했습니다 호출 된 메소드 내부. vf 함수에 국부적 및 main() 함수에 유사하게 명명 된 변수는 아무런 관계가없는 vi

void input_instructions(double vi, double vf) 
{ 
. 
. 
} 

변수에

+0

main 함수에서 두 함수의 변수를 서로 로컬로 만드는 방법은 무엇입니까? –

+0

함수는 스택에서만 사용할 수있는 자체 변수를 스핀 업합니다. 다른 함수에서는 사용할 수 없으며 함수가 끝나자 마자 스택에서 정리됩니다. main에 의해 호출 된 함수는 main으로부터 변수에 접근하지도 않습니다. 내가 제공 한 첫 번째 해결책은 지역 변수가 아닌 전역 변수를 사용합니다. 전역 변수는 스택이 아닌 힙에 만들어 지므로 솔루션 전체에서 액세스 할 수 있습니다. –

+0

두 번째 솔루션은 참조로 통과를 사용합니다. 새로운 변수는 여전히 main에 의해 호출되는 함수 내부에서 스핀 업되지만, 매개 변수를 통해 main에있는 값에 대한 스택의 메모리 위치를 전달합니다. 이렇게하면 스택의 일부에 영향을주는 변경을 수행 할 수 있습니다. 일반적으로에 액세스 할 수 있습니다. –

0

. 즉, 그들은 function-scope을 가지며 함수가 반환 된 후에는 더 이상 존재하지 않습니다.

input_instructions(&vi,&vf); // pass the address in the main() 

과 같은 기능을 재 작성 :

당신이 해왔해야 할 것은있는 공식적인 인수를 사용하여 영구적 인 변화가 main()vfvi로 만들어진 여기

void input_instructions(double *vi, double *vf) // Using pointers 
{ 
    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); // Hmm, you're changing the value in the main() 
    printf("Enter final velocity"); 
    scanf("%lf", vf); // Note no '&' since we're dealing with pointers. 
} 

*vf*viinput_instructions입니다.

관련 문제