【问题标题】:Whats wrong with this code? (function and values)这段代码有什么问题? (功能和价值)
【发布时间】:2015-12-25 14:17:59
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int getAge(void);

int main(void)
{
    int age = 0;
    getAge();
    printf("The age is %4d\n",age);
     system("PAUSE");
      return 0;
 }

 //The function gets the age until it is valid, and returns the vaild age
int getAge(void)
{
    const int MAX_AGE = 120;
   const int MIN_AGE = 0;
    int age = 0;
   int invalidAge = 0;
    printf("please enter your age (0-120): ");
    do
    {
        scanf("%d", &age);
        invalidAge = ( age > MAX_AGE || age < MIN_AGE );
        if( invalidAge )
        {
            printf("Invalid age! Please enter your age (0-120): ");
        }
    } while ( invalidAge );
    printf("Finally!!!\n");
    return age;
}

您好,此代码存在运行时问题。谁能告诉我要改什么? 没有编译错误。

【问题讨论】:

  • 什么运行时问题?它做错了什么?我发现至少有两个问题,但除了“它不起作用”之外,您还需要给我们提供更多信息。
  • 请参考一些好的编程书籍,例如 Dennis Ritchie Programming in c。

标签: c function return function-call


【解决方案1】:

这里的问题是,在您的代码中,

 getAge();

您忘记将getAge(); 函数的返回值收集到age 变量中。因此getAge()函数的返回值总是被忽略,输出为0。

您需要将代码更改为

  age = getAge();

将要存储的函数的返回值存储到age中。

【讨论】:

  • 应该改变哪一行?
  • 不是我..感谢您帮助我
  • 但是为什么它会给出编译时错误?..你是说...返回值没有存储在age...但是为什么这是一个问题???... .如果返回值没有存储在age中,那么打印age应该打印0..对吧?
  • 是否必须将返回值存储在变量中??
  • @MathewsMathai:这不应该是编译错误。你得到编译错误了吗?
【解决方案2】:

请在“年龄”变量中捕获返回值,如下所示。

 int main(void)
    {
        int age = 0;
       age= getAge(); //catch the return value
        printf("The age is %4d\n",age);
         system("PAUSE");
          return 0;
     }

【讨论】:

    猜你喜欢
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多