关于函数的返回类型

about return type from a function

本文关键字:返回类型 函数 于函数      更新时间:2023-10-16

在这里,我写了一些代码,从一个函数中获得一个数字的平方,但返回语句不像我想要的那样工作,它给了我相同的数字,我已经进入,我想知道背后的原因,请如果有人可以解释这个给我…

#include<iostream>
#include<conio.h>
using namespace std;
int square(int &i);
int main()
{
    cout<<"enter the number whose square you want to find";
    int a;
    cin>>a;
    square(a);
    cout<<"the square of the number is"<<a;
    _getch();
    return 0;
}
int square(int &i)
{
    return i*i;
}

您忽略了返回值。您应该将其存储为:

int value = square(a);
cout<<"the square of the number is "<< value;

同样,由于类型只是整型,通过引用传递不会给您带来太多好处。出于可读性考虑,我建议使用按值传递:

int square(int i)
{
    return i*i;
}

,

或者如果你正在尝试引用,并试图学习它,那么在这种情况下,我会说你必须将product的结果存储在参数本身中,如:

int square(int &i)
{
    i = i * i; //this updates i here, and at the call site as well
    return i; 
}

或者简单地这样做:

int square(int &i)
{
   return i = i*i; //multiply, update, and return - all in one statement!
}

未获取结果。你的台词应该是:a = square(a);从函数中获取结果。另一种可能是写入函数

int square(int &i)
{
    i = i * i;
    return i;
}

后者将改变传递给函数的变量,从而证明传递引用是合理的。


要想清楚地表明你想改变变量,可以这样做:

void square(int &i)
{
    i = i * i;
}

你看这里没有返回,但是它会改变变量的值

你有一个选择:

  1. 修改传入的参数,或者
  2. 返回一个值并将其赋值给调用范围内的某个对象。

你在square中所做的是第二个选择。你似乎想要前者。

如果你真正想要的是修改传入的值,那么你需要这样做:

void square(int &i)
{
    i = i*i;
}

这样做:

  a = Square (a) ; // in main()
  ...
int Square (int i) // Pass by value -- doesn't change a in main
  {
  return i * i ;
  }

这样做:

  Square (a) ; // in main()
  ...
void Square (int& i) // Pass by reference -- changes a in main
  {
  i = i * i ; // No need for a return value
  }

在编写其他程序之前,请确保理解它们的区别!

从你对答案的评论来看,你误解了引用传递的作用,或者你误解了返回。

我假设你认为变量I将在你的程序中被更新。然而,事实并非如此。如果你做了像…

i = i*i;

那么是的,你是正确的。但是,您没有给i赋任何值,您只是将其自身乘以并返回结果。此外,如果您确实希望基于引用使此工作,则不需要返回任何内容,因为变量将通过引用更新。