0

我一直在自学 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);
}
4

1 回答 1

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);
}
于 2012-09-21T21:35:11.317 回答