我试图在这里进行函数调用,但是我不知道出了什么问题。我收到一个错误:
无法重载功能
我们必须使用switch
大小写。如果有人可以帮助解决此问题,那就太好了。
// Include Section
#include <iostream>
#include <cstdlib>
using namespace std;
//Function prototype
double rectangle(double, double);
double triangle(double, double);
double circle(double);
// Main Program
int main()
{
//Variable declaration
int choice;
const double PI = 3.14159; //pi
double area;
double length, //length for rectangle
width; //width for rectangle
double height; //height for triangle
double base; //base for triangle
double radius; //radius for circle
//Give choices
cout << "Welcome to Geometry Calculator \n";
cout << "Pick one option from the following: \n";
cout << "1. Calculate the Area of a Rectangle \n";
cout << "2. Calculate the Area of a Triangle \n";
cout << "3. Calculate the Area of a Circle \n";
cout << "4. Quit \n\n";
//input choice
cout << "Enter your choice (1-4): ";
cin >> choice;
//Input Validation
while (choice <= 0 || choice > 4)
{
cout << "Please enter a valid menu chice: ";
cin >> choice;
}
//Switch statement
switch (choice)
{
case 1: //rectangle
cout << "Enter the LENGTH of your Rectangle: ";
cin >> length;
cout << "Enter the WIDTH of your Rectangle: ";
cin >> width;
rectangle(length, width);
//function
break;
case 2: //Triangle
cout << "Enter the LENGTH of the base of your Triangle: ";
cin >> base;
cout << "Enter the HEIGHT of your Triangle: ";
cin >> height;
triangle(base, height);
return 0;
break;
case 3: //Circle
cout << "Enter the RADIUS of your Circle: ";
cin >> radius;
circle(radius);
return 0;
//calculation
break;
case 4: //quit
cout << "You chose to quit. Thanks for using my program! \n\n";
}
return 0;
}
//function call
void triangle(double base, double height);
{
area = base * height * 0.5;
cout << "The AREA of your Triangle is " << area << ". \n\n";
}
void circle(double radius);
{
area = PI * radius * radius;
cout << "The AREA of your Circle is " << area << ". \n\n";
}
double fc = rectangle(double length, double width);
{
area = length * width;
cout << "The area of the rectangle is " << area << endl;
}
您在这里有多个问题:
在函数定义上,尾随的分号不应存在:
void triangle(double base, double height); // <-- remove this semicolon
{
area = base * height * 0.5;
cout << "The AREA of your Triangle is " << area << ". \n\n";
}
此错误在其他定义上也存在。分号终止函数前向声明(在文件顶部),但是在定义函数时,括号将其替换。
您还声明了三个函数triangle
/circle
/ rectangle
以返回double
,但是在实现中,您将它们定义为返回不匹配的void
。这可能是您收到的特定错误的来源。
更改前向声明以匹配定义,反之亦然。
这三个函数还试图分配一个不在范围内的area
变量。如果要在其中使用此变量,则必须在这些函数中声明它。
请注意,这些功能无法访问area
中的main()
变量。
rectangle
的定义以变量声明开头,这没有任何意义:
double fc = rectangle(double length, double width);
这被解析为全局
fc
变量的声明,该声明已初始化为调用rectangle
函数的结果,但是参数语法不正确,因此解析将在那里失败。大概应该这样写:
void rectangle(double length, double width)
或
double rectangle(double length, double width)
功能
circle()
引用符号PI
,但这不在范围内。 (您在PI
内部声明了main()
,因此它仅在该函数中可见。您可以通过将其移至全局范围来解决此问题。)