我正在尝试使用一个函数来使用存储在结构中的变量来计算答案。每当我编译代码时,我都会遇到有关struct成员的每次使用的错误。我哪里错了?
干杯!
#include <iostream>
using namespace std;
struct rectangle
{
double length, width, area, perimeter; // measurements for rectangle
};
int calculations()
{
rect.area = rect.width * rect.length;
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
}
int main()
{
rectangle rect; // rect is a rectnagle structure
cout << "Please enter the length of your rectangle: " << endl;
cin >> rect.length;
cout << "Please enter the width of your rectnagle: " << endl;
cin >> rect.width;
calculations();
cout << "The area of your rectangle is: " << rect.area << endl;
cout << "The perimieter of your rectnagle is: " << rect.perimeter << endl;
cout << rect.length << endl;
cout << rect.width << endl;
cout << rect.area << endl;
cout << rect.perimeter << endl;
}
生成的错误是:
Untitled.cpp:15:5: error: use of undeclared identifier 'rect'
rect.area = rect.width * rect.length;
^
Untitled.cpp:15:17: error: use of undeclared identifier 'rect'
rect.area = rect.width * rect.length;
^
Untitled.cpp:15:30: error: use of undeclared identifier 'rect'
rect.area = rect.width * rect.length;
^
Untitled.cpp:17:5: error: use of undeclared identifier 'rect'
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
^
Untitled.cpp:17:22: error: use of undeclared identifier 'rect'
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
^
Untitled.cpp:17:35: error: use of undeclared identifier 'rect'
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
^
Untitled.cpp:17:48: error: use of undeclared identifier 'rect'
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
^
Untitled.cpp:17:62: error: use of undeclared identifier 'rect'
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
^
8 errors generated.
答案 0 :(得分:2)
添加参数:
void calculations(rectangle& rect)
{
rect.area = rect.width * rect.length;
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
}
然后致电:
calculations(rect);
答案 1 :(得分:0)
您尚未声明rect:
int calculations()
{
rect.area = rect.width * rect.length;
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
}
在你的例子中移动:
rectangle rect; // rect is a rectnagle structure
使其全球化:
};
rectangle rect; // rect is a rectnagle structure
int calculations()
{
答案 2 :(得分:0)
void calculations(rectangle &rect)
{
rect.area = rect.width * rect.length;
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
}
尝试使用它,因为在计算函数范围内没有定义rect
答案 3 :(得分:0)
您的函数的问题在于它使用的名称rect不是全局的,并且是在函数定义之后定义的。所以函数什么都不知道什么是rect。
将功能重新定义为
void calculations( rectangle &rect )
{
rect.area = rect.width * rect.length;
rect.perimeter = rect.width + rect.width + rect.length + rect.length;
}
并在main中将其称为
calculations( rect );