编写使用C ++返回值的函数

时间:2018-10-08 02:22:17

标签: c++ return-value

我的编程课入门有这个作业,由于终端不断显示此错误,我遇到了麻烦:

Calculator.cpp:在“ int main()”函数中:

Calculator.cpp:30:10:警告:“ result”可能未在此函数中使用[-Wmaybe-uninitialized]

result = sum(numberOne,numberTwo,result);

这是我当前的C ++代码

// Calculator.cpp - This program performs arithmetic, ( +. -, *. / ) on two numbers.
// Input:  Interactive
// Output:  Result of arithmetic operation

#include <iostream>
#include <string>
using namespace std;

// Write performOperation() function declaration here
double sum(double numberOne, double numberTwo, double result);
double difference(double numberOne, double numberTwo, double result);
double product(double numberOne, double numberTwo, double result);
double quotient(double numberOne, double numberTwo, double result);

int main()
{
   double numberOne, numberTwo;
   string operation;
   double result;

   cout << "Enter the first number: ";
   cin >> numberOne;
   cout << "Enter the second number: ";
   cin >> numberTwo;
   cout << "Enter an operator (+.-.*,/): ";
   cin >> operation;

   // Call performOperation method here
   if (operation == "+")
       result = sum(numberOne, numberTwo, result);
   else if (operation == "-")
       result = difference(numberOne, numberTwo, result);
   else if (operation == "*")
       result = product(numberOne, numberTwo, result);
   else if (operation == "/")
       result = quotient(numberOne, numberTwo, result);
   else
       cout << "Please enter a valid operator." << endl;

   if (operation == "+" || operation == "-" || operation == "*" || operation == "/")

   {
       cout << numberOne;
       cout << " " << operation << " ";
       cout << numberTwo;
       cout << " = ";
       cout << result << endl;
   }

   return 0;

} // End of main() function

// Write perform Operation function here

double sum(double numberOne, double numberTwo, double result)
{
   result = numberOne + numberTwo;
   return result;
}

double difference(double numberOne, double numberTwo, double result)
{
   result = numberOne - numberTwo;
   return result;
}

double product(double numberOne, double numberTwo, double result)
{
   result = numberOne * numberTwo;
   return result;
}

double quotient(double numberOne, double numberTwo, double result)
{
   result = numberOne / numberTwo;
   return result;
}

我尝试将结果初始化为0.0,但随后出现错误。我们使用这种参与学习的东西,它仅显示80%完成。

double result=0.0;

1 个答案:

答案 0 :(得分:3)

问题源于您对每个函数的第三个争论:

double sum(double numberOne, double numberTwo, double result);
                                               ^^^^^^^^^^^^^

您不需要将result in 传递给函数,因为您将在return语句中返回结果。删除第三个参数,调整对函数的所有调用,您将避免此警告。

收到此警告的原因是编译器看到了对sum()的调用,或者看到了您正在传递的值result,但是result尚未初始化。由于您根本不需要传递它,因此删除该参数可以解决此问题。