模拟画图功能
模拟计算机的画图功能,能够模拟画圆和长方形的功能。程序主要功能如下:
① 提供一个如下的主菜单。
*******************************
1. Circle (圆)
2. Rectangle (长方形)
0. Exit (退出)
*******************************
② 不断接受用户的选择(整数),直至用户选择 0 为止。如果用户输入了系统尚未支持的选择(比如 3),则给出相应的提示信息,并继续选择。
③ 如果用户选择了圆或长方形,则进一步提示用户输入两个点,分别称为起点和终点,如下图所示。坐标仅考虑正整数的情况。要求终点的坐标大于起点的坐标,否则给出相关的提示信息并返回主菜单。
④ 模拟画出圆和长方形。画圆时,要计算 startPoint 和 endPoint 所构成的正方形的内切圆的圆心和半径。若 startPoint 和 endPoint 所构成的不是正方形,则给出相关的提示信息并返回主菜单。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// 表示平面上点的结构体
struct Point {
double x;
double y;
};
// 显示主菜单
void displayMenu();
// 得到用户输入的两个点
void getTwoPoints(struct Point* p1, struct Point* p2);
// 以 (x, y) 的形式打印点
void printPoint(struct Point* p);
// 画圆的函数
void drawCircle(struct Point* p1, struct Point* p2);
// 画长方形的函数
void drawRectangle(struct Point* p1, struct Point* p2);
int main() {
int choice = 1;
struct Point startP, endP;
while (choice) {
displayMenu();
cin >> choice;
switch (choice) {
case 1:
getTwoPoints(&startP, &endP);
drawCircle(&startP, &endP);
break;
case 2:
getTwoPoints(&startP, &endP);
drawRectangle(&startP, &endP);
break;
case 0:
cout << "Good bye!\n";
break;
default:
cout << "Not supported! Please select again!\n";
break;
}
}
return 0;
}
void displayMenu() {
cout << "*********************************" << endl;
cout << " 1. Circle(圆) " << endl;
cout << " 2. Rectangle(长方形) " << endl;
cout << " 0. Exit(退出) " << endl;
cout << "*********************************" << endl;
cout << "Please select the shape: " << endl;
}
void getTwoPoints(struct Point* p1, struct Point* p2) {
double x1, y1, x2, y2;
while (true) {
cout << "The end point should be greater than the start point. " << endl;
cout << "Please input the coordinate (x, y) of the start point: ";
cin >> x1 >> y1;
cout << "Please input the coordinate (x, y) of the end point: ";
cin >> x2 >> y2;
if (x2 > x1 && y2 > y1) {
p1->x = x1;
p1->y = y1;
p2->x = x2;
p2->y = y2;
break;
} else {
cout << "Not supported! Please input again!" << endl;
}
}
}
void printPoint(struct Point* p) {
cout << "(" << setprecision(6) << p->x << ", "
<< setprecision(6) << p->y << ")";
}
void drawCircle(struct Point* p1, struct Point* p2) {
double xDiffer = p2->x - p1->x;
double yDiffer = p2->y - p1->y;
if (xDiffer == yDiffer) {
double radius = xDiffer / 2;
double xCenter = p1->x + radius;
double yCenter = p1->y + radius;
cout << "Draw a circle at center (" << setprecision(6) << xCenter << ", "
<< setprecision(6) << yCenter << ") with radius "
<< setprecision(6) << radius << endl;
} else {
cout << "Not a circle! Please select again!\n";
}
}
void drawRectangle(struct Point* p1, struct Point* p2) {
double xDiffer = p2->x - p1->x;
double yDiffer = p2->y - p1->y;
cout << "Draw a rectangle at topleft ";
printPoint(p1);
cout<<", whose width is " << setprecision(6)<< xDiffer
<< " and height is " << setprecision(6) << yDiffer << endl;
}