为什么不返回修改函数的参数值

可能重复:
如何修改通过值传递的原始变量的内容?

我正在构建一个非常简单的程序来计算矩形的面积。 但是很简单,因为你会注意到我似乎无法获得返回值。 我一直看到0.可能有一个明显的答案,或者有些事我不明白。 inheritance我的代码:

#include //prototypes int FindArea(int , int , int); main() { //Area of a Rectangle int rBase,rHeight,rArea = 0; //get base printf("\n\n\tThis program will calculate the Area of a rectangle."); printf("\n\n\tFirst, enter a value of the base of a rectangle:"); scanf(" %d" , &rBase); //refresh and get height system("cls"); printf("\n\n\tNow please enter the height of the same rectangle:"); scanf(" %d" , &rHeight); //refresh and show output system("cls"); FindArea (rArea , rBase , rHeight); printf("\n\n\tThe area of this rectangle is %d" , rArea); getch(); }//end main int FindArea (rArea , rBase , rHeight) { rArea = (rBase * rHeight); return (rArea); }//end FindArea 

您将rArea初始化为0.然后, 按值将其传递给FindArea 。 这意味着函数中对rArea的更改都没有反映出来。 您也没有使用返回值。 因此, rArea保持为0。

选项1 – 使用返回值:

 int FindArea(int rBase, int rHeight) { return rBase * rHeight; } rArea = FindArea(rBase, rHeight); 

选项2 – 通过引用传递:

 void FindArea(int *rArea, int rBase, int rHeight) { *rArea = rBase * rHeight; } FindArea(&rArea, rBase, rHeight); 

您需要将FindArea的返回值分配给rArea 。 目前, FindArea将产品分配给同名的本地变量。

或者,您可以传递mainrArea的地址来修改它,看起来像

 FindArea(&rArea, rBase, rHeight); 

main

 void FindArea(int * rArea, int rBase, int rHeight) { *rArea = rBase * rHeight; } 
 FindArea (rArea , rBase , rHeight); 

不像你认为的那样工作。 在C中,参数按值传递; 这意味着修改函数内的area只会修改它的本地副本。 您需要将函数的返回值赋给变量:

 int FindArea(int w, int h) { return w * h; } int w, h, area; // ... area = findArea(w, h); 

因为您没有存储返回值。 代码不会以其当前forms编译。

  1. 称之为:

     rArea = (rBase , rHeight); 
  2. 将function更改为:

     int FindArea (int rBase ,int rHeight) { return (rBase * rHeight); } 
  3. 将原型更改为:

     int FindArea(int , int); 

那是因为你永远不会在主程序中为rArea分配另一个值而不是0。

通过指针获取rArea

 int FindArea(int *, int , int); ... FindArea (&rArea , rBase , rHeight); ... int FindArea (int *rArea , int rBase , int rHeight) { *rArea = (rBase * rHeight); return (*rArea); } 

您的基本问题是您不了解如何从函数中获取值。 将相关行更改为:

 int FindArea(int rBase, int rHeight); // prototype 

 int area = FindArea(rBase, rHeight); 

 int FindArea(int rBase, int rHeight) { return rBase * rHeight; }