我能够解决这个问题的唯一方法是创建全局变量float x, y;,然后在整个程序中使用它们。我对编程很陌生,因为这很明显,但我听说创建全局变量通常是一种不好的做法。
我的猜测是问题出现在void completeOperation(int z){}函数中,因为错误消息基本上表明变量 x 和 y 都没有被声明。当我在该范围内声明它们时,它要求我给它们一个值,而我需要用户在 main.xml 中输入所述值。
我怎样才能使这项工作?原谅我不得不把整个代码放上去。它很小。
#include <iostream>
using namespace std;
void createMenu();
void completeOperation(int z);
float add(float x, float y);
float subtract(float x, float y);
float multiply(float x, float y);
float divide(float x, float y);
float greaterNumber(float x, float y);
float lesserNumber(float x, float y);
int main()
{
float x, y;
cout << "Enter the first real number value." << endl;
cin >> x;
cout << "Enter the second real number value." << endl;
cin >> y;
createMenu();
int z;
cin >> z;
completeOperation(z);
system("pause");
}
void createMenu()
{
cout << "\nChoose a desired arithmetic operation by entering a number from 1 to 6. \n\n";
cout << "1.) Addition \n2.) Subtraction \n3.) Multiplication \n4.) Division \n5.) Bigger number \n6.) Smaller number" << endl;
}
void completeOperation(int z)
{
switch (z)
{
case 1:
cout << "\nAddition: " << add(x, y) << endl;
break;
case 2:
cout << "\nSubtraction: " << subtract(x, y) << endl;
break;
case 3:
cout << "\nMultiplication: " << multiply(x, y) << endl;
break;
case 4:
cout << "\nDivision: " << divide(x, y) << endl;
break;
case 5:
cout << "\nBigger number: " << greaterNumber(x, y) << endl;
break;
case 6:
cout << "\nSmaller number: " << lesserNumber(x, y) << endl;
break;
}
}
float add(float x, float y)
{
return (x + y);
}
float subtract(float x, float y)
{
return (x - y);
}
float multiply(float x, float y)
{
return (x * y);
}
float divide(float x, float y)
{
return (x / y);
}
float greaterNumber(float x, float y)
{
if (x > y)
{
return x;
}
else return y;
}
float lesserNumber(float x, float y)
{
if (x < y)
{
return x;
}
else return y;
}