簡體   English   中英

如何在C中返回int值?

[英]How to return an int value in C?

我是C語言的新手,正在嘗試創建一個簡單的程序來返回名稱和年齡。 我創建了一個用於返回名稱的工作函數,但對於返回int無效。

我現在擁有的代碼是:

int * GetAge(){  
  int Age;

  printf("What is your age: ");
  scanf(" %d", &Age);

  int * returnedage = Age;

  return returnedage;
}

這是GetName():

char * GetName(){
  char Name[31];

  printf("What is your name: ");
  scanf("%s", Name);

  char * returnedname = Name;

  return returnedname;
}

警告在此行上:

int * returnedage = Age;

它說:

incompatible integer to pointer conversion
initializing 'int *' with an expression of type 'int'; take
the address with &

我努力了:

int * returnedage * Age;
int * returnedage & Age;
//for strcpy I set the function as a char
char * returnedage;
strcpy(Age, returnedage);

這些都不起作用。

我只想獲取名稱和年齡,然后我主要使用以下命令打印名稱和年齡:

printf("Your name is %s and your age is %d", GetName(), *GetAge());

這沒有任何錯誤。

所以我的預期輸出是:

What is your name: Ethan
What is your age: 13
Your name is Ethan and your age is 13

我實際上得到的是:

What is your name: ethan
What is your age: 13
exit status -1

請告訴我是否有一個基本的解決方案。

將代碼更改為此:

int GetAge()
{  
  int Age;

  printf("What is your age: ");
  scanf(" %d", &Age);

  return Age;
}

在主菜單上(刪除GetAge()上的*):

printf("Your name is %s and your age is %d", GetName(), GetAge());

您的事情太復雜了。 再次閱讀您用來學習C的資料,以更好地了解正在發生的事情。

編輯:將您的GetName()更改為:

void GetName(char *name){

  printf("What is your name: ");
  scanf("%s", name);
}

現在主要:

char name[31];
GetName(name);
printf("Your name is %s and your age is %d", name, GetAge());

這樣做的原因是C無法返回字符數組(這就是您要嘗試完成的事情)。 相反,您可以給該函數一個位於main()中的局部變量的內存地址,並將用戶的輸入存儲到該變量中。

嘗試:

int GetAge()
{ 
    int Age;
    printf("What is your age: ");
    if (scanf("%d", &Age) != 1)
        return -1;  // return an error code if an integer couldn't be read
    return Age;
}

現在使用GetAge()調用函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM