关于函数的返回类型

nob*_*alG 0 c++ return-value

这里我写了一些代码来从函数中得到一个数字的平方,但是return语句没有按照我的意愿运行,它给了我输入的相同数字,我想知道背后的原因,如果有人可以向我解释这个请...

#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;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 6

你忽略了返回的值.你应该把它存储为:

int value = square(a);
cout<<"the square of the number is "<< value;
Run Code Online (Sandbox Code Playgroud)

此外,由于类型只是整数类型,因此通过引用不会给您带来太多好处.为了便于阅读,我建议使用pass by值:

int square(int i)
{
    return i*i;
}
Run Code Online (Sandbox Code Playgroud)

-

或者,如果您正在尝试参考并尝试学习它,那么在这种情况下我会说您要将产品的结果存储在参数本身中,如下所示:

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

或者只是这样做:

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