【发布时间】:2020-06-06 02:00:50
【问题描述】:
这个想法是根据定义的结构和枚举以表格格式显示从用户收集的所有数据。我收到了一些关于使用 switch 语句的警告,但最令人讨厌的事情似乎是在尝试显示值时使用“s.width”。当我尝试编译时,它建议它在 s.width 中的 s 之前需要一个分号,并且它会继续将分号移动到下一个值。我从枚举中引用值的方式有什么不正确的地方吗?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//TODO 1: ShapeKind Enumeration goes here
enum class ShapeKind{
CIRCLE,SQUARE,RECTANGLE
};
//TODO 2: Shape Structure goes here
struct Shape{
ShapeKind kind;
double length, width;
};
// Function prototypes and definitions
double area(Shape s);
//TODO 3: area() definition goes here
double area(Shape s){
double a;
switch(s.kind){
case ShapeKind::CIRCLE:
return a= (s.length * s.width * 3.14) /4 ;
case ShapeKind::SQUARE:
return a = s.length *s.length;
case ShapeKind::RECTANGLE:
return a = s.length * s.width;
}
}
double perimeter(Shape s);
//TODO 4: perimeter() definition goes here
double perimeter(Shape s){
double p;
switch(s.kind){
case ShapeKind::CIRCLE:
return p= s.length * 3.14;
case ShapeKind::SQUARE:
return p = s.length *4;
case ShapeKind::RECTANGLE:
return p = 2 *(s.length + s.width);
}
}
string nameOf(Shape s);
//TODO 5: nameOf() definition goes here
string nameof(Shape s){
switch(s.kind){
case ShapeKind::CIRCLE:
return "Circle";
case ShapeKind::SQUARE:
return "Square";
case ShapeKind::RECTANGLE:
return "Rectangle";
}
}
void promptAndReadInputFor(Shape& shape);
//TODO 6: promptAndReadInputFor() definition goes here
void promptAndReadInputFor(Shape& s){
switch(s.kind){
case ShapeKind::CIRCLE:
cout <<"Enter the diameter or a circle: "<< endl;
cin >> s.length;
s.width =s.length;
case ShapeKind::SQUARE:
cout << "Enter the length of one side: "<< endl;
cin >>s.length;
s.width=s.length;
case ShapeKind::RECTANGLE:
cout << "Enter the length and width: "<< endl;
cin >>s.length>>s.width;
if (s.length == s.width)
{
s.kind = ShapeKind::SQUARE;
}
}
};
// The main function
int main() {
// Shape objects
Shape circle = { ShapeKind::CIRCLE, 0, 0 };
//TODO 7: define two more shape objects: a square and and a rectangle
Shape square= {ShapeKind::SQUARE, 0, 0};
Shape rectangle ={ShapeKind::RECTANGLE, 0, 0};
//TODO 8: Call the promptAndReadInputFor() function on each of the above three shapes
promptAndReadInputFor(circle);
promptAndReadInputFor(square);
promptAndReadInputFor(rectangle);
//TODO 9: Print a out a report of these shapes in a table-like format
cout << setw(4) << "Shape" << setw(4) << "Width" << setw(4) << "Height" << setw(4) << "Perimeter"<< setw(4) << "Area"<<endl;
cout << setw(4) << nameOf(circle) << setw(4) s.width << setw(4) s.length << setw(4) perimeter(circle)<< setw(4) << area(circle)<< endl;
return 0;
}
【问题讨论】: