简体   繁体   中英

My program won't calculate the age correctly and won't accept my input

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

int main()
{    
    int _age;//declare variable
    getAge();//calls function
    welcomeMessage();//calls function

    return 0;   
}

int getAge(int _age)//takes input from user and assigns a value to age
{
    printf("What is your age?\n");
    scanf("%d", &_age);
}

int welcomeMessage(int _age)//prints how old you are
{   
    printf("Welcome, you are %d years old.\n", _age);   
}

I keep getting a random number for the age and I need to recognize what I put in for scanf

Your int getAge(int _age) function should be like the following:

void getAge(int* _age)
{
   printf("What is your age?\n");
   scanf("%d", _age);
}

and in your main() function you need to call int welcomeMessage(int _age) as the following:

int main()
{    
    int _age;               // declare variable
    getAge(&_age);          // calls function
    welcomeMessage(_age);   // calls function

    return 0;
}

And actually, a more correct version of your code should be like the following:

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

void getAge(int*);
void welcomeMessage(int);

int main()
{
    int _age;               
    getAge(&_age);          
    welcomeMessage(_age);   
    return 0;
}

void getAge(int* _age)
{
   printf("What is your age?\n");
   scanf("%d", _age);
}

void welcomeMessage(int _age)
{
   printf("Welcome, you are %d years old.\n", _age)
}

Consider re-writing getAge() . Be sure to check the result of scanf() .

int getAge(void) {
  int age;
  printf("What is your age?\n");
  if (1 == scanf("%d", &age)) {
    return age;
  }
  printf("Trouble with input\n");
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM