第二个用户定义的函数返回垃圾值?

时间:2012-09-21 21:18:44

标签: variables garbage

我一直在自学C编程,而且我在使用函数变量时遇到了困难。

当我编译该程序并运行它时,函数askBirthYear返回正确的值,但sayAgeInYears返回0或垃圾值。我相信它与我如何使用变量birthYear有关,但我很难解决问题。

以下是代码:

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

int askBirthYear(int);
void sayAgeInYears(int);
int birthYear;

int main(void)
{    askBirthYear(birthYear);
     sayAgeInYears(birthYear);
     return EXIT_SUCCESS;
}

int askBirthYear(int birthYear)
{
    printf("Hello! In what year were you born?\n");
    scanf("%d", &birthYear);
    printf("Your birth year is %d.\n", birthYear);
    return birthYear;
}

void sayAgeInYears(int birthYear)
{
    int age;
    age = 2012 - birthYear;
    printf("You are %d years old.\n", age);
}

1 个答案:

答案 0 :(得分:1)

简单。你将birthYear传递给askBirthYear,而不是通过引用。然后你只需将其返回值放在地板上。你对askBirthYear的声明及其定义也有不同意见。

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

int askBirthYear(void);
void sayAgeInYears(int);
int birthYear;

int main(void)
{
     birthYear = askBirthYear();
     sayAgeInYears(birthYear);
     return EXIT_SUCCESS;
}

int askBirthYear(void)
{
    int year;
    printf("Hello! In what year were you born?\n");
    scanf("%d", &year);
    printf("Your birth year is %d.\n", year);
    return year;
}

void sayAgeInYears(int birthYear)
{
    int age;
    age = 2012 - birthYear;
    printf("You are %d years old.\n", age);
}