-3

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

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

#include<stdio.h>

//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
4

7 回答 7

3

你初始化rArea为 0。然后,你将它传递给FindArea value。这意味着函数中的任何更改都不会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);
于 2012-10-02T23:09:56.257 回答
1

Because you are not storing the return value. The code won't compile in its present form.

  1. Call it as:

    rArea = (rBase , rHeight);
    
  2. Change the function to:

    int FindArea (int rBase ,int rHeight)  
    {  
        return (rBase * rHeight);  
    }
    
  3. Change the prototype to:

    int FindArea(int , int);
    
于 2012-10-02T23:09:30.207 回答
1

您需要分配 to 的返回FindArearArea。目前,FindArea将产品分配给同名的局部变量。

或者,您可以传递main's的地址rArea来修改它,看起来像

FindArea(&rArea, rBase, rHeight);

main

void FindArea(int * rArea, int rBase, int rHeight) {
    *rArea = rBase * rHeight;
}
于 2012-10-02T23:09:52.973 回答
1
FindArea (rArea , rBase , rHeight);

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

int FindArea(int w, int h) { return w * h; }

int w, h, area;

// ...
area = findArea(w, h);
于 2012-10-02T23:10:31.390 回答
0

That's because you never assign another value than 0 to rArea in your main program.

于 2012-10-02T23:08:45.263 回答
0

take rArea by pointer:

int FindArea(int *, int , int);

...

FindArea (&rArea , rBase , rHeight);

...



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

 return (*rArea);

}
于 2012-10-02T23:08:46.000 回答
0

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

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

int area = FindArea(rBase, rHeight);

int FindArea(int rBase, int rHeight)
{
     return rBase * rHeight;
}
于 2012-10-02T23:09:38.260 回答