【问题标题】:im getting 32767 in my output c++ program我在我的输出 C++ 程序中得到 32767
【发布时间】:2023-04-01 12:10:01
【问题描述】:

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

【问题讨论】:

    标签: c++ function boolean


    【解决方案1】:

    您通过值传递total,这意味着addition() 无法修改maintotal 变量。而是通过引用传递:

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

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

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

    随后是:

    if (result)
    

    【讨论】:

    • 另外,他返回 -1 而不是 0。IIRC 0 是唯一计算结果为假的整数。
    • 不错 - 没注意到那个。
    【解决方案2】:

    您通过 total 的值传递。改用指针或引用在addition 函数中修改其值。

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

    【讨论】:

      【解决方案3】:

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

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

      而不是

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

      此外,您的条件if (1) 始终为真。所以你总会得到low

      【讨论】:

        【解决方案4】:
        #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;
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2014-01-24
          • 1970-01-01
          • 2021-12-15
          • 1970-01-01
          • 1970-01-01
          • 2017-09-25
          • 2013-07-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多