-4

这段代码只需要一个数字,将它加到另一个数字上,然后将结果打印出来。它还说明了数字是高还是低。这一切都在一个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

4 回答 4

2

您正在total按值传递,这意味着addition()无法修改main'total变量。通过引用传递:

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

你总是得到“它的低”的原因是因为if (1)它总是正确的。可能你想要类似的东西:

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

紧随其后的是:

if (result)
于 2013-10-01T17:15:49.420 回答
2

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

此外,从具有布尔返回类型的函数返回1或返回具有相同的效果,就像在 C++ 中任何非零值的计算结果一样。返回或(或某个非零值或 0)。-1truetruefalse

于 2013-10-01T17:18:45.917 回答
0

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

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

代替

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

你的条件if (1)也总是正确的。所以你总是会低落

于 2013-10-01T17:16:11.517 回答
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;
    }

}
于 2013-10-01T17:18:03.777 回答