为什么此代码末尾返回一个长数字? (C ++)

时间:2020-09-09 23:14:01

标签: c++

#include <iostream>
using namespace std;

int funky(int stuff)
{
    int number;
    number = 10;
    cout << "Please enter a number \n";
    cin >> number;
    stuff = number + 777;
    cout << "The result is " << stuff << endl;
    return 0;
}

int main()
{
    int num1, num2;
    
    funky(num1);
    funky(num2);
    
    cout << num1 << "  and  " << num2;
    
    return 0;
}

我正在尝试学习在C ++中使用函数,但是我无法弄清楚为什么这段代码最后会返回一个很长的负数。有人可以告诉我为什么num2返回一个很长的数字吗?对我来说根本没有意义

2 个答案:

答案 0 :(得分:2)

显然,您的意图是在函数内分配stuff并在num1中用作num2main()。为此,您需要将参数类型从int更改为int&,即按引用传递。您的函数声明应为int funky(int& stuff)

您定义函数的方式,变量num1num2仍未初始化,这就是cout << num1 << " and " << num2;正在打印垃圾的原因。

答案 1 :(得分:1)

您的代码有些错误。首先,您不需要返回值的函数。您可以改用void

您还通过不初始化变量int num1int num2来获得Undefined Behavior

现在,解决问题的另一种方法是使用void。 (如果您只需要两个数字。)除此之外,我建议使用@Eugene的答案。

替换:

int funky(int stuff)void funky(int stuff)

例如:

#include <iostream>
using namespace std;

void funky()
{
    int num1 = 0;
    int num2 = 0;

    cout << "Please enter a number \n";
    cin >> num1;
    int Res1 = num1 + 777;
    cout << "The result is " << Res1 << endl;


    cout << "Please enter one more number \n";
    cin >> num2;
    int Res2 = num2 + 777;

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


    cout << num1 << " and " << num2;
    
    
}

int main()
{

    funky();

    return 0;
}