首页 > 解决方案 > c++中的函数错误

问题描述

我正在从一本名为“跳转到c++”的书中学习c++中的函数,并且有一个问题练习是创建一个计算器,我需要在单独的函数中进行算术运算,听起来很容易,我认为我做到了 90% 好,该程序给了我正确的答案,但有一些随机数。

代码是:

#include <iostream>

using namespace std;

int a, b;

int sum()
{

       return a + b;

}

int subs()
{

    return a - b;

}

int div()
{

    return a / b;

}

int mult()
{

    return a * b;

}

int ask()
{

    cout << "Give me the first number: ";
    cin >> a;
    cout << "\nGive me the second number: ";
    cin >> b;

}

int main()
{

    int opcion;

    cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
    cin >> opcion;

    if(opcion == 1)
    {

        cout << ask();

        cout << "The result is: " <<sum() <<"\n\n";

    } else if (opcion == 2)
      {

          cout << ask();

          cout << "The result is: " << subs() <<"\n\n";

      }else if (opcion == 3)
        {

            cout <<ask();

            cout << "The result is: " << div() <<"\n\n";

        }else if(opcion == 4)
         {

            cout << ask();

             cout << "The result is: " << mult() <<"\n\n";

         }else
            {

                cout << "Error.\n\n";

            }

    system("pause");

}

这就是“错误/错误/无论如何”

1. Sum
2. Substraction
3. Division
4. Multiplication

Choose one option from above:

4
Give me the first number: 5

Give me the second number: 5
1878005856The result is: 25

Press any key to continue . . .

注意“结果是:”之前的错误

感谢任何帮助,谢谢

标签: c++function

解决方案


ask()不返回任何东西,所以它应该是无效的。另外,您不需要这样做,cout << ask();因为ask()已经在其中进行了打印,并且它是无效的(现在),因此无法打印。

这是修改后的代码,请参阅前面带有 **** 的注释以进行更改:

#include <iostream>

using namespace std;

int a, b;

int sum() {
  return a + b;
}

int subs() {
  return a - b;
}

int div() {
  return a / b;
}

int mult() {
  return a * b;
}

void ask() { // **** Changed to void here
  cout << "Give me the first number: ";
  cin >> a;
  cout << "\nGive me the second number: ";
  cin >> b;
}

int main() {
  int opcion;

  cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
  cin >> opcion;

  if (opcion == 1) {
    ask(); // **** Removed cout << 
    cout << "The result is: " << sum() << "\n\n";
  } else if (opcion == 2) {
    ask(); // **** Removed cout << 
    cout << "The result is: " << subs() << "\n\n";
  } else if (opcion == 3) {
    ask(); // **** Removed cout << 
    cout << "The result is: " << div() << "\n\n";
  } else if (opcion == 4) {
    ask(); // **** Removed cout << 
    cout << "The result is: " << mult() << "\n\n";
  } else {
    cout << "Error.\n\n";
  }
  system("pause");
}

你可以在这里试试

随机数是由您造成的,cout << ask();即使您没有返回任何东西。

正如 aschepler 指出的那样“确保启用并阅读编译器警告 - 应该有人说 ask() 尽管声明返回一个 int,但不会返回任何东西。”


推荐阅读