我在输出c ++程序中获得32767

时间:2013-10-01 17:14:11

标签: c++ function boolean

此代码只需一个数字,将其添加到另一个数字,然后输出结果。它还说这个数字是高还是低。这都是在bool函数中完成的:

#include <iostream>

using namespace std;
bool addition(int num, int num2, int total);

int main()
{
    int num, num2,total;
    cout << "enter a number"<< endl;
    cin >> num;
    cout<< "enter another number" << endl;
    cin >> num2;
    addition(num, num2, total);
    {
        cout <<"the first number is:" <<  num<< " the second number is: "<< num2 <<   endl; 
        cout << "the total is: " << total << endl;
        if (1) {
            cout << "its low" ;
        } else {
            cout << "its high";
        }
        cout << endl;
    }

}

bool addition (int num, int num2, int total) {
    //total = 0;
    total = num + num2;
    if (total >= 10){
        return 1;
    } else { 
        return -1;
    }
}

问题是这个程序总是说数字很低,总数总是32767.我不知道为什么。

4 个答案:

答案 0 :(得分:2)

您按值total传递,这意味着addition()无法修改main的{​​{1}}变量。通过引用传递:

total

你总是得到“低”的原因是因为bool addition (int num, int num2, int &total) 总是如此。可能你想要这样的东西:

if (1)

稍后通过:

bool result = addition(num, num2, total);

答案 1 :(得分:2)

您正在传递total的值。使用指针或引用来修改addition函数内的值。

此外,从具有布尔返回类型的函数返回1-1具有相同的效果,如在C ++中,任何非零值的计算结果为true。返回truefalse(或某些非零值或0)。

答案 2 :(得分:0)

尝试通过引用传递total而不是像这样的值:

bool addition (int num, int num2, int &total)

而不是

bool addition(int num, int num2, int total);

此外,您的条件if (1)始终为真。因此,您将始终获得

答案 3 :(得分:0)

#include <iostream>

using namespace std;
bool addition (int num, int num2, int &total) {
    total = num + num2;
    return total >= 10;
}

int main()
{
    int num, num2,total;
    cout << "enter a number"<< endl;
    cin >> num;
    cout<< "enter another number" << endl;
    cin >> num2;
    bool additionResult = addition(num, num2, total);
    {
        cout <<"the first number is:" <<  num<< " the second number is: "<< num2 <<   endl; 
        cout << "the total is: " << total << endl;
        if (!additionResult){
            cout << "its low" ;
        }
        else{
            cout << "its high";
        }
        cout << endl;
    }

}