您能告诉我代码有什么问题吗?

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

int main()

{

    int CurrentYear;
    int BornYear;
    int age = CurrentYear - BornYear;

    printf("What year is it?\n");
    scanf("%d", &CurrentYear);
    //printf("Year check: %d\n", CurrentYear);
    printf("What year you were born?\n");
    scanf("%d", &BornYear);
    //printf("Year check: %d\n", BornYear);
    printf("You are %d years old\n", age);
    return 0;
}


结果我得到一些奇怪的数字。

最佳答案

C中的表达式不是公式。这个:

int age = CurrentYear - BornYear;


并不意味着age的值将始终为CurrentYear - BornYear。这意味着在代码的这一点上,根据那些变量的当前值将age设置为CurrentYear - BornYear。这两个变量都未初始化,因此它们的值不确定。

阅读ageCurrentYear之后,需要将BornYear的计算移至:

int CurrentYear;
int BornYear;
int age;

printf("What year is it?\n");
scanf("%d", &CurrentYear);
printf("What year you were born?\n");
scanf("%d", &BornYear);

age = CurrentYear - BornYear;
printf("You are %d years old\n", age);

关于c - 试图计算年龄在C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55229930/

10-15 01:36