为什么不返回修改参数的值的函数 [英] Why doesn't return modify the value of a parameter to a function

查看:144
本文介绍了为什么不返回修改参数的值的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/9938096/how-to-modify-content-of-the-original-variable-which-is-passed-by-value\">How要修改的是按值传递的原始变量的内容?


我建立一个pretty简单的程序,计算出的矩形的面积。够简单不过,因为你会发现我似乎无法得到一个返回值。我不断看到有0可能是一个明显的答案或许有件事我只是不明白。我的继承人code:

 #包括LT&;&stdio.h中GT;//原型
INT FindArea(INT,INT,INT);主要()
{矩形的面积//  INT RBASE,rHeight,rArea = 0;  //获取基地
  的printf(\\ n \\ n \\ tThis程序会计算一个矩形的面积。);
  输出(\\ n \\ n \\ tFirst输入一个矩形的基座的一个值:);
  scanf函数(%d个,&安培; RBASE);  //刷新并获得高度
  系统(CLS);
  的printf(\\ n \\ n \\ TNOW请输入相同的矩形的高度:);
  scanf函数(%d个,&安培; rHeight);  //刷新并显示输出
  系统(CLS);
  FindArea(rArea,RBASE,rHeight);
  的printf(\\ n \\ n \\这个矩形的面积里边反为%d,rArea);
  残培();} //主到底INT FindArea(rArea,RBASE,rHeight)
{
 rArea =(RBASE * rHeight); 回报(rArea);} //结束FindArea


解决方案

您intialize rArea 0。然后,它传递到 FindArea 按值。这意味着没有任何的变化 rArea 在函数反映。你不使用的返回值,无论是。因此, rArea 0停留

选项1 - 使用的返回值:

  INT FindArea(INT RBASE,诠释rHeight){
    返回RBASE * rHeight;
}rArea = FindArea(RBASE,rHeight);

选项2 - 按引用传递:

 无效FindArea为(int * rArea,诠释RBASE,诠释rHeight){
    * rArea = RBASE * rHeight;
}FindArea(安培; rArea,RBASE,rHeight);

Possible Duplicate:
How to modify content of the original variable which is passed by value?

I am building a pretty simple program that calculates the area of a rectangle. Simple enough however, as you will notice I cannot seem to get a return value. I keep seeing 0. There is probably an obvious answer or perhaps there is something I just don't understand. Heres my code:

#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

解决方案

You intialize rArea to 0. Then, you pass it into FindArea by value. This means none of the changes to rArea in the function are reflected. You don't make use of the return value, either. Therefore, rArea stays 0.

Option 1 - Use the return value:

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

rArea = FindArea(rBase, rHeight);

Option 2 - Pass by reference:

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

FindArea(&rArea, rBase, rHeight);

这篇关于为什么不返回修改参数的值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆