这是我的程序,它找到一个矩形的区域,周长,如果矩形是方形的。它通过使用两个坐标和建模结构完成所有这些。我对C ++很新,我在这一行上得到一个不熟悉的错误:if(abs(y-a2.y)= abs(a2.x - x)){错误说明:赋值时非左值。< / p>
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Rectangle
Author: ------
Date: 27/10/14 04:31
Description: A program that finds the area, perimeter, and if a rectangle is square
*/
using namespace std;
class Point
{
private:
int x, y;
public:
Point ()
{
x = 0;
y = 0;
}
//A four parameter constructor
Point (int a, int b)
{
x = a ;
y = b ;
}
//Setter function
void setX (int a)
{
x = a ;
}
void setY (int b)
{
y = b ;
}
//Accessor functions
int getX ()
{
return x ;
}
int getY ()
{
return y ;
}
//Function to print points
void printPoint ()
{
cout << endl << "(" << x << ", " << y << ")" << endl ;
}
//Function to enter new points
Point newPoint ()
{
Point aPoint;
int a;
int b;
cout << "Enter first x coordinate: " ;
cin >> a ;
cout << "Enter first y coordinate: " ;
cin >> b ;
aPoint.setX(a);
aPoint.setY(b);
return aPoint;
}
//Function to find area
int areaA (Point a2)
{
int height = y - a2.y ;
int length = a2.x - x ;
int area = abs((length * height)) ;
return area ;
}
//Function to find perimeter
int perimeterA (Point a2)
{
int height1 = y - a2.y ;
int length1 = a2.x - x ;
int perimeter1 = abs(((length1 + height1) * 2)) ;
return perimeter1 ;
}
//Function to determine shape
int isSquare (Point a2)
{
int square;
if ( abs(y - a2.y) = abs(a2.x - x) ) //****ERROR ON THIS LINE****
{
cout << "It is square" ;
}
else
{
cout << "It is not square" ;
}
return square;
}
};
Point newPoint();
int main(int argc, char *argv[])
{
cout << "Enter top left coordinate first and bottom right coordinate second" ;
cout << endl << endl ;
Point firstPoint;
Point secondPoint;
int areaR;
int perimeter;
firstPoint = firstPoint.newPoint();
secondPoint = secondPoint.newPoint();
cout << endl ;
cout << "First point: " ;
firstPoint.printPoint();
cout << "Second point: " ;
secondPoint.printPoint();
cout << endl ;
areaR = firstPoint.areaA(secondPoint);
cout << "Area: " << areaR << endl ;
perimeter = firstPoint.perimeterA(secondPoint);
cout << "Perimeter: " << perimeter << endl;
cout << endl ;
system("PAUSE");
return EXIT_SUCCESS;
}
答案 0 :(得分:4)
if(abs(y-a2.y) = abs(a2.x - x) )
尝试将abs(a2.x - x)
分配给abs(y-a2.y)
,这是没有意义的。使用==
来比较值。
顺便说一句,isSquare
返回一个未初始化的值,这是一个错误。要么返回有意义的函数void
。
答案 1 :(得分:2)
我在这个错误中没有看到任何奇怪的东西。该行确实尝试将某些内容分配给非左值,正如错误消息所述。在C ++中,等式比较运算符拼写为==
。表达式上下文中的单个=
是赋值运算符。
还不清楚为什么在包含C库标题时混合两种不同的样式:<cstdlib>
和<math.h>
。如果您决定加入<cstdlib>
,那么包含<cmath>
会更有意义。请记住,通过<c...>
标头提供的标准库函数应被视为std
命名空间的成员。现代C ++中不推荐使用.h
版本的heqaders。