如何在另一个函数内部使用带有参数的函数的返回值 [英] How to use the return value of a function with parameters inside another function

查看:57
本文介绍了如何在另一个函数内部使用带有参数的函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有这些函数都在int main()之外:

All these functions are outside the int main():

int func1(int x) {

    int v1 = 6 * x;
    return v1; // the input argument will be 2, so v1 = 12
}

int func2(){
    int v2 = func1() / 4; // It's suppose to be 12 / 4
    //I get "too few arguments in function call"
 }

我知道第二个函数中的 func1()缺少参数,这就是发出参数过多"警告的原因.我想知道的是如何使用 func2()内的 func1()的返回值作为变量的值.

I know func1() inside 2nd function lacks arguments, that's the reason for the "too few arguments" warning. What I want to know is how can I use the return value of func1() inside func2(), as a value to a variable.

像这样,没有参数的函数可以正常工作:

Like this, with functions without parameters, which work fine:

     int sum() {

        int v1 = 10;
        int v2 = 4;
        int v3 = v1 + v2; // 10 + 4 = 14
        return v3; // v3 = 14
    }

    int sub() {

        int v4 = sum() - 7; // 14 - 7 = 7;
        return v4; // v4 = 7
 }

谢谢.

对不起,当我说我了解警告的原因时,我以为自己很清楚.我的错.

EDIT : Sorry, I thought I had made myself clear when I said I understood the reason for the warning. My mistake.

我需要用户在功能1中的输入是可变的.

I need the input from the user in function 1 to be variable.

因此,在main()中,当提示用户提供数字时,它将被传递给函数1.参数不是固定的,而是可变的.

So, in main(), when the user is prompted to give a number, it will be passed to function 1. The argument is not fixed, it is variable.

这是主体背后的想法:

int main() {
    int x = 0;
    cin >> x;
    func1(x); // send user input to func1, then to func2
    int e = func2(); // return result of above to int e
    cout << e << "\n";


}

推荐答案

您会收到此错误,因为您必须为函数提供所需的所有参数.您没有为函数提供参数,因此该函数不起作用.sum()不接收任何参数,因此必须这样调用

You get this error because you have to give the function all the arguments it needs. You are not giving an argument to a function so it will not work. sum() doesnt receive any arguments so it has to be called like this

sum()

func1()接受一个参数,因此请将其更改为不接受参数的函数

func1() takes one argument so either change it to a function that takes no arguments

int func1() {

    int v1 = 6 * 2;
    return v1; // the input argument will be 2, so v1 = 12
}

但是它表明您没有考虑自己在做什么,这一点都没用

but it shows that you havent thought about what you are doing and its kinda useless

或这样调用它而不更改功能

or call it like this without changing the function

int v2 = func1(2) / 4;

编辑
因此,您可以更改func2以获得一个参数并将其传递给func1

EDIT
So you can change func2 to also get one argument and pass it to func1

int func2(int x){
    int v2 = func1(x) / 4;
 }

主要是

int x;
cin>>x;
func2(x);

这也是您的func2()应该返回int但又没有return语句的小东西

also small thing your func2() should return int but you dont have a return statement

这篇关于如何在另一个函数内部使用带有参数的函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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