【问题标题】:Having issues with this simple program这个简单的程序有问题
【发布时间】:2022-01-01 17:29:44
【问题描述】:

该程序只是简单地通过从当前年份中减去他们的出生日期来计算用户年龄。当我运行程序时,它编译成功,但我得到一个很长的数字,例如 -215863352。添加 if 和 else 条件只是为了测试它们,我正在使用它们编写各种程序以确保我理解 c 中的语法。我想我错过了一些简单但无法弄清楚的东西。

#include <stdio.h>
int main()
{
    int year;
    int cyear;
    int age = cyear - year;

    printf("Please enter the year you were born: \n");
    scanf("%i", &year);
    printf("Now enter the current year: \n");
    scanf("%i", &cyear);

    if (1+1 == 2){
        printf("You must be %i", age);
    }
    else {
        printf("Cannot compute age, GOODBYE:\n");
    }
    return 0;
}

【问题讨论】:

  • 1:指令是顺序执行的,程序不是Excel Sheet,你需要把int age = cyear - year;放在scanfs之后。 2:1 + 1 == 2 始终为真,因此if 在这里毫无意义。
  • 将age初始化为int,然后在scanf后面加上age = cyear - year
  • C 源代码从上到下依次执行。您的初学者 C 级书籍应该解释这一点。
  • 任何相当不错的编译器都应该报告指向原因的警告:“main.c(6) : 警告 C4700: 未初始化的局部变量 'cyear', 'year' used. 因此,使用默认值初始化这些变量在计算中使用它们之前的值。

标签: c macos if-statement integer conditional-statements


【解决方案1】:

您正在计算从用户获取输入之前的年龄。所以age 变量存储了一个垃圾值。

解决方案:

在使用 scanf 获取cyear 的输入之后,定位从用户获取输入之后的年龄计算。正确的代码如下 #include

int main()
{
    int year;
    int cyear;
    int age =0;     //initialise with 0

    printf("Please enter the year you were born: \n");
    scanf("%i", &year);
    printf("Now enter the current year: \n");
    scanf("%i", &cyear);
    
    age = cyear - year;     //note the change here

    if (1+1 == 2){
        printf("You must be %i", age);
    }
    else {
        printf("Cannot compute age, GOODBYE:\n");
    }
    return 0;
}

【讨论】:

    【解决方案2】:
    enter code here
       #include <stdio.h>
       int main()
       {
      long long int year;
      printf("Please enter the year you were born: \n");
    scanf("%lld",&year);
    long long int cyear;
      printf("Now enter the current year: \n");
    scanf("%lld",&cyear);
    
    long long  int age = cyear-year;
    
    if (1){
        printf("You must be %lld", age);
    }
    else {  printf("Now enter the current year: \n");
    scanf("%lld",&cyear);
    
        printf("Cannot compute age, GOODBYE:\n");
    }
    return 0;
    

    }

    【讨论】:

    • 好像是初始化问题出现了。
    • 嗨,欢迎来到 SO!请包括对您的答案的解释,而不仅仅是代码。 :)
    • 如果在初始化之前有一个计算(例如age=cyear_year)会导致错误的答案,因为你不知道你的变量的当前装载量。它会从内存中获取一些值。跨度>
    猜你喜欢
    • 2016-10-20
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 2011-10-31
    • 2010-09-26
    相关资源
    最近更新 更多