使用按引用调用计算两个数字中的最大数字 [英] Calculating the largest number out of two numbers using call by reference

查看:89
本文介绍了使用按引用调用计算两个数字中的最大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的讲师给了我一个任务,就是通过参考想法来调用这两个数字中最大的一个。我总是在函数中使用值调用,实际上这是我第一次通过引用学习使用call。所以,在展示我的讲师之前,如果我的程序是正确的,我的程序想要寻求一些建议。任何评论(只要不是冒犯性的)都将受到高度赞赏。



My lecturer gave me the task of using the call by reference idea to find the largest out of two numbers. I have always used call by value in a function and actually this is the first time i learnt using call by reference. So, before showing my lecturer my program wanted to seek some advise if my program is correct. Please any comments(as long as it is not offensive) will be highly appreciated.

double largestfun(double &num1, double &num2)
{
    double *temp;
    double *zamp;

    temp = &num1;
    zamp = &num2;

    //return (max(*temp,*zamp));
    if(*temp>*zamp)
    {
        return (*temp);
    }
    else
        return (*zamp);


}

int main()

{
double a, b;
double result;


cout<<"Enter two numbers"<<endl;
cin>>a>>b;

result = largestfun(a,b);

cout<<"The result is:"<<result"<<endl;


system("pause");

}

推荐答案

你需要什么? 和 zamp 变量?



What do you need the local temp and zamp variable for?

double largestfun(double &num1, double &num2)
{
    //double *temp;
    //double *zamp;

    //temp = &num1;
    //zamp = &num2;

    //return (max(*temp,*zamp));
    if(num1 > num2)
    {
        return (num1);
    }
    else
        return (num2);


}


您的代码是正确的,但不必要的复杂。这就是通常的做法。

Your code is correct, but unnecessarily complicated. This is how it normally would be done.
double largestfun (double &num1, double &num2)
{
    if (num1 > num2)
        return num1;
    else
        return num2;
}



或者更简单:


Or yet simpler:

double largestfun (double &num1, double &num2)
{
    return num1 > num2 ? num1 : num2;
}



它与呼叫引用无关。同样适用于按值调用。


And it has nothing to do with call by-reference. The same would work equally well with call by value.


如果不修改函数中引用的实体,请将它们作为const引用。

例如。
If you do not modify the referenced entities in your function, make them const references.
E.g.
double max_double(const double &a, const double & b) { return a < b ? b : a; }



有趣的问题是,为什么/何时使用引用来代替按值调用?

干杯

Andi



PS:对你的代码的评论:



  • 参考如果不修改参数,则应为const - 这是惯用的C ++
  • 块语句的不一致使用:用于两个分支(if和else)块语句,即 {.. 。}
  • 过于复杂:为什么在本地变量中存储参数?
  • 使用名称temp对我来说是一个红旗:如果你失败了给你不错的名字,你要么懒惰,要么不理解问题(你可能会说我为什么使用a和b而不是其他名称:可能的推理是它们是可互换的任意参数 - 我更喜欢名字/单个字符而非编号参数)
  • 为什么要指定对指针的引用?!这在技术上是可能的,但在其他方面是完全错误的引用的想法是在函数中包含外部实体的别名 - 因此,可以通过名称直接访问引用。如果你取一个引用的地址,那么你迟早要处理一个死对象的可能性很高。只要停止采取参考地址的习惯。如果程序的逻辑是需要传递0对象的,则通过允许传递0指针的指针传递对象。

  • 这篇关于使用按引用调用计算两个数字中的最大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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