为什么不返回修改参数的值的函数 [英] Why doesn't return modify the value of a parameter to a function
问题描述
可能重复:结果
<一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 intoFindArea
by value. This means none of the changes torArea
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屋!